带你读《现代TypeScript高级教程》四、接口和类(1)https://developer.aliyun.com/article/1348557?groupCode=tech_library
TypeScript 类还支持继承,通过extends关键字可以创建一个子类。子类可以访问和改变父类的属性和方法:
class Animal { name: string; constructor(theName: string) { this.name = theName; } move(distanceInMeters: number = 0) { console.log(`this.namemoved{this.name} moved {distanceInMeters}m.`); }} class Dog extends Animal { constructor(name: string) { super(name); } bark() { console.log('Wo of! Woof!'); }} const dog = new Dog('Tom'); dog.bark(); dog.move(10); dog.bark();
为了实现多态,TypeScript 提供了抽象类的概念。抽象类是不能被实例化的类,只能作为其他类的基类。抽象类中可以定义抽象方法,抽象方法必须在派生类中实现:
abstract class Animal { abstract makeSound(): void; move(): void { console.log('roaming the earth...'); }} class Dog extends Animal { makeSound() { console.log('Woof! Woof!'); }} const myDog = new Dog(); myDog.makeSound(); myDog.move();