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

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[];
}
主站蜘蛛池模板: 巢湖市| 高淳县| 迁安市| 温宿县| 城口县| 任丘市| 都匀市| 上虞市| 甘泉县| 云霄县| 汉阴县| 武邑县| 达拉特旗| 宜黄县| 汝州市| 日照市| 十堰市| 文安县| 商南县| 昭通市| 夏河县| 张家口市| 双城市| 馆陶县| 怀柔区| 江城| 吴桥县| 扶余县| 香格里拉县| 磐石市| 宝坻区| 扎鲁特旗| 昔阳县| 特克斯县| 志丹县| 章丘市| 马边| 和平县| 北京市| 青川县| 深州市|