abstract
Classes and Members
TypeScript 中的类、方法和字段可能是抽象的。
抽象方法或抽象字段是一种尚未提供实现的方法。 这些成员必须存在于抽象类中,不能直接实例化。
抽象类的作用是作为实现所有抽象成员的子类的基类。 当一个类没有任何抽象成员时,它被称为具体的。
看个例子:
abstract class Base { abstract getName(): string; printName() { console.log("Hello, " + this.getName()); } } const b = new Base(); Cannot create an instance of an abstract class.
我们不能用 new 实例化 Base,因为它是抽象的。 相反,我们需要创建一个派生类并实现抽象成员:
class Derived extends Base { getName() { return "world"; } } const d = new Derived(); d.printName();
8
请注意,如果我们忘记实现基类的抽象成员,我们会得到一个错误:
class Derived extends Base { Non-abstract class 'Derived' does not implement inherited abstract member 'getName' from class 'Base'. // forgot to do anything }
4
Abstract Construct Signatures
有时,您希望接受某个类构造函数,该函数生成从某个抽象类派生的类的实例。
例如,您可能想编写以下代码:
function greet(ctor: typeof Base) { const instance = new ctor(); Cannot create an instance of an abstract class. instance.printName(); }
TypeScript 正确地告诉你你正在尝试实例化一个抽象类。 毕竟,考虑到greet的定义,编写这段代码是完全合法的,最终会构造一个抽象类:
// Bad! greet(Base);