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

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[];
}
主站蜘蛛池模板: 南澳县| 旺苍县| 云和县| 泸水县| 房产| 萝北县| 甘孜县| 安吉县| 芜湖县| 乌拉特前旗| 上杭县| 塘沽区| 广宗县| 九江县| 乌恰县| 霞浦县| 双流县| 海伦市| 浪卡子县| 玉林市| 娱乐| 昭通市| 张家口市| 牙克石市| 蒲江县| 宁武县| 辉南县| 布拖县| 锡林郭勒盟| 宜君县| 安化县| 清新县| 永和县| 长葛市| 古浪县| 三河市| 墨脱县| 沈阳市| 开原市| 和平区| 平湖市|