- Learn React with TypeScript 3
- Carl Rippon
- 201字
- 2021-06-10 19:16:35
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:
- 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[];
}
- 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 }
];
- 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[];
}
推薦閱讀
- 多媒體CAI課件設(shè)計(jì)與制作導(dǎo)論(第二版)
- 從零開(kāi)始:數(shù)字圖像處理的編程基礎(chǔ)與應(yīng)用
- 自己動(dòng)手實(shí)現(xiàn)Lua:虛擬機(jī)、編譯器和標(biāo)準(zhǔn)庫(kù)
- Android開(kāi)發(fā)精要
- Python Deep Learning
- Practical DevOps
- Nginx Essentials
- 深度強(qiáng)化學(xué)習(xí)算法與實(shí)踐:基于PyTorch的實(shí)現(xiàn)
- Learning Salesforce Einstein
- H5頁(yè)面設(shè)計(jì):Mugeda版(微課版)
- Android開(kāi)發(fā)案例教程與項(xiàng)目實(shí)戰(zhàn)(在線實(shí)驗(yàn)+在線自測(cè))
- Learning Unity 2D Game Development by Example
- Julia高性能科學(xué)計(jì)算(第2版)
- Node Cookbook(Second Edition)
- JavaScript+jQuery網(wǎng)頁(yè)特效設(shè)計(jì)任務(wù)驅(qū)動(dòng)教程