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

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[];
}
主站蜘蛛池模板: 沂南县| 利川市| 长顺县| 南江县| 辽源市| 伊宁市| 大冶市| 达州市| 鞍山市| 阜新市| 渝中区| 双辽市| 容城县| 武清区| 澎湖县| 娱乐| 玉屏| 安龙县| 东光县| 阿拉善左旗| 庐江县| 迁西县| 根河市| 长子县| 梁河县| 武夷山市| 衡东县| 苏尼特左旗| 上虞市| 辽宁省| 迁西县| 桑日县| 德清县| 古丈县| 和龙市| 松潘县| 上高县| 东乌| 绍兴市| 荥阳市| 托里县|