【TypeScript】抽象类的使用 | 类的类型
warning:
这篇文章距离上次修改已过187天,其中的内容可能已经有所变动。
在TypeScript中,我们可以使用抽象类来定义一种模板,这个模板包含了一些抽象的方法和属性,继承了抽象类的子类需要实现这些抽象方法和属性。抽象类不能直接实例化,只能用于继承。
下面是一个使用抽象类的例子:
abstract class Animal {
// 抽象属性,子类必须实现
abstract name: string;
// 抽象方法,子类必须实现
abstract makeSound(): void;
// 具体方法
move(): void {
console.log('Animals can move.');
}
}
class Dog extends Animal {
name: string;
constructor(name: string) {
super();
this.name = name;
}
makeSound(): void {
console.log('Woof! My name is ' + this.name);
}
}
class Cat extends Animal {
name: string;
constructor(name: string) {
super();
this.name = name;
}
makeSound(): void {
console.log('Meow! My name is ' + this.name);
}
}
let myDog = new Dog('Rex');
let myCat = new Cat('Whiskers');
myDog.makeSound(); // Output: Woof! My name is Rex
myCat.makeSound(); // Output: Meow! My name is Whiskers
在这个例子中,Animal
是一个抽象类,它定义了 name
抽象属性和 makeSound
抽象方法。Dog
和 Cat
类继承了 Animal
类,并且实现了所有抽象的属性和方法。这样,我们就可以在 Dog
和 Cat
类中定义具体的行为,而不用在 Animal
类中重复实现相同的逻辑。
评论已关闭