TS class类的定义、extends类的继承、属性修饰符、implements类的接口实现、abstract抽象类
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
在TypeScript中,定义一个类使用class
关键字,可以通过extends
继承另一个类,实现接口使用implements
。属性可以用访问修饰符如public
,private
,protected
或readonly
来修饰。抽象类和方法使用abstract
关键字。
以下是一个简单的例子:
// 定义一个接口
interface IAnimal {
name: string;
makeSound(): void;
}
// 实现接口的抽象类
abstract class Animal implements IAnimal {
public name: string;
constructor(name: string) {
this.name = name;
}
abstract makeSound(): void;
}
// 继承抽象类的具体类
class Dog extends Animal {
constructor(name: string) {
super(name);
}
makeSound() {
console.log(`Woof! My name is ${this.name}`);
}
}
// 使用
const myDog = new Dog('Rex');
myDog.makeSound(); // 输出: Woof! My name is Rex
在这个例子中,IAnimal
是一个接口,定义了所有动物应该有的属性和方法。Animal
是一个抽象类,实现了IAnimal
接口,但是makeSound
方法是抽象的,必须在子类中实现。Dog
类继承自Animal
类,提供了makeSound
方法的具体实现。
评论已关闭