TypeScript 抽象类
摘要:在本教程中,你将了解 TypeScript 抽象类以及如何使用它们来定义派生类的常见行为。
TypeScript 抽象类简介
抽象类通常用于定义派生类的常见行为。 与常规类不同,抽象类不能直接实例化。
要声明抽象类,可以使用 abstract 关键字:
abstract class Employee {
//...
}
通常,抽象类包含一个或多个抽象方法。
抽象方法不包含实现。 它只定义了方法的签名,不包括方法体。 抽象方法必须在派生类中实现。
下面显示了具有 getSalary() 抽象方法的 Employee 抽象类:
abstract class Employee {
constructor(private firstName: string, private lastName: string) {
}
abstract getSalary(): number
get fullName(): string {
return `${this.firstName} ${this.lastName}`;
}
compensationStatement(): string {
return `${this.fullName} makes ${this.getSalary()} a month.`;
}
}
在 Employee 类中:
- 构造函数声明
firstName和lastName属性。 getSalary()方法是一个抽象方法。 派生类将根据员工的类型实现逻辑。getFullName()和compensationStatement()方法包含详细的实现。 请注意,compensationStatement()方法调用getSalary()方法。
由于 Employee 类是抽象类,因此无法从中创建新对象。 以下语句会导致错误:
let employee = new Employee('John','Doe');
报错:
error TS2511: Cannot create an instance of an abstract class.
以下 FullTimeEmployee 类继承自 Employee 类:
class FullTimeEmployee extends Employee {
constructor(firstName: string, lastName: string, private salary: number) {
super(firstName, lastName);
}
getSalary(): number {
return this.salary;
}
}
在此 FullTimeEmployee 类中,在构造函数中设置了 salary。 由于 getSalary() 是 Employee 类的抽象方法,因此 FullTimeEmployee 类需要实现该方法。 在这个例子中,它只是返回工资,没有任何计算。
下面显示了同样继承自 Employee 类的 Contractor 类:
class Contractor extends Employee {
constructor(firstName: string, lastName: string, private rate: number, private hours: number) {
super(firstName, lastName);
}
getSalary(): number {
return this.rate * this.hours;
}
}
在 Contractor 类中,构造函数初始化了费率和工时。 getSalary() 方法通过将费率乘以小时来计算工资。
下面首先创建一个 FullTimeEmployee 对象和一个 Contractor 对象,然后将薪酬语句显示到控制台:
let john = new FullTimeEmployee('John', 'Doe', 12000);
let jane = new Contractor('Jane', 'Doe', 100, 160);
console.log(john.compensationStatement());
console.log(jane.compensationStatement());
输出:
John Doe makes 12000 a month.
Jane Doe makes 16000 a month.
当你想在一些相关类之间共享代码时,使用抽象类是一个很好的做法。
概括
- 抽象类不能被实例化。
- 抽象类至少有一个抽象方法。
- 要使用抽象类,你需要继承它并提供抽象方法的实现。