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

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[];
}
主站蜘蛛池模板: 台前县| 突泉县| 大名县| 吉林市| 灌南县| 定南县| 富裕县| 嘉祥县| 松滋市| 全州县| 长春市| 巫溪县| 定襄县| 南昌市| 溧水县| 镇安县| 封丘县| 鹰潭市| 镇安县| 厦门市| 区。| 灌云县| 乡宁县| 兴海县| 项城市| 故城县| 十堰市| 嫩江县| 汶上县| 玉屏| 宿州市| 大田县| 定安县| 黔西县| 股票| 鹤庆县| 禹城市| 望江县| 吴川市| 河间市| 卓尼县|