- 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[];
}
推薦閱讀
- LabVIEW Graphical Programming Cookbook
- Power Up Your PowToon Studio Project
- 數據庫系統(tǒng)原理及MySQL應用教程
- 數據結構(Python語言描述)(第2版)
- Hands-On Microservices with Kotlin
- Mastering Linux Network Administration
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(2)
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- Django 3.0入門與實踐
- 3ds Max印象 電視欄目包裝動畫與特效制作
- 從零開始學UI:概念解析、實戰(zhàn)提高、突破規(guī)則
- Java程序設計(項目教學版)
- 開發(fā)者測試
- Scratch 3少兒交互式游戲編程一本通
- Unity3D游戲開發(fā)標準教程