- 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[];
}
推薦閱讀
- VMware View Security Essentials
- Learning Cython Programming
- UML和模式應用(原書第3版)
- Java系統分析與架構設計
- Spring技術內幕:深入解析Spring架構與設計
- Mastering Natural Language Processing with Python
- Spring Boot進階:原理、實戰與面試題分析
- Visual C#通用范例開發金典
- Node.js開發指南
- .NET 4.5 Parallel Extensions Cookbook
- 平面設計經典案例教程:CorelDRAW X6
- 軟件體系結構
- Python趣味編程與精彩實例
- Java并發實現原理:JDK源碼剖析
- C Primer Plus(第6版)中文版【最新修訂版】