- 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[];
}
推薦閱讀
- Data Visualization with D3 4.x Cookbook(Second Edition)
- 流量的秘密:Google Analytics網(wǎng)站分析與優(yōu)化技巧(第2版)
- Learning Docker
- 算法精粹:經(jīng)典計(jì)算機(jī)科學(xué)問(wèn)題的Java實(shí)現(xiàn)
- C/C++常用算法手冊(cè)(第3版)
- 征服RIA
- Interactive Applications Using Matplotlib
- SQL Server 2016數(shù)據(jù)庫(kù)應(yīng)用與開(kāi)發(fā)習(xí)題解答與上機(jī)指導(dǎo)
- Learning Zurb Foundation
- PHP+MySQL+Dreamweaver動(dòng)態(tài)網(wǎng)站開(kāi)發(fā)從入門到精通(第3版)
- 區(qū)塊鏈技術(shù)與應(yīng)用
- RESTful Java Web Services(Second Edition)
- Visual Studio 2015高級(jí)編程(第6版)
- Learning Node.js for .NET Developers
- SpringBoot從零開(kāi)始學(xué)(視頻教學(xué)版)