官术网_书友最值得收藏!

Extending classes

Classes can extend other classes. This is the same concept as interfaces extending other interfaces, which we covered in the Extending interfaces section. This is a way for class properties and methods to be shared with child classes.

As with interfaces, we use the extends keyword followed by the class we are extending. Let's look at an example:

  1. Let's create a ProductWithDiscountCodes from our Product class:
class Product {
name: string;
unitPrice: number;
}

interface DiscountCode {
code: string;
percentage: number;
}

class ProductWithDiscountCodes extends Product {
discountCodes: DiscountCode[];
}
  1. We can then consume the ProductWithDiscountCodes class as follows, leveraging properties from the base class as well as the child class:
const table = new ProductWithDiscountCodes();
table.name = "Table";
table.unitPrice = 500;
table.discountCodes = [
{ code: "SUMMER10", percentage: 0.1 },
{ code: "BFRI", percentage: 0.2 }
];
  1. If the parent class has a constructor, then the child class will need to pass the constructor parameters using a function called super:
class Product {
constructor(public name: string, public unitPrice: number) {
}
}

interface DiscountCode {
code: string;
percentage: number;
}

class ProductWithDiscountCodes extends Product {
constructor(public name: string, public unitPrice: number) {
super(name, unitPrice);
}
discountCodes: DiscountCode[];
}
主站蜘蛛池模板: 水城县| 华坪县| 中西区| 沙湾县| 丰城市| 永和县| 汉川市| 仁怀市| 瑞丽市| 多伦县| 巢湖市| 射洪县| 社会| 荔浦县| 延津县| 柯坪县| 佛教| 佛教| 时尚| 灵台县| 麦盖提县| 南和县| 关岭| 奎屯市| 仪陇县| 新蔡县| 修水县| 湖南省| 文登市| 华蓥市| 大埔县| 阳信县| 阿城市| 乐至县| 马鞍山市| 两当县| 新干县| 托里县| 扬中市| 乐山市| 镇沅|