在打字稿中是否可以强制所有派生类都具有带有预定义签名的构造函数?
不,不可能阻止扩展类对构造函数使用不同的签名。
但是,您可以通过使用静态方法来解决此问题,该方法将为您提供所需的类型安全性:
class A {
static instantiate<T extends A>(this: { new (...args: ConstructorParameters<typeof A>): T }, ...args: ConstructorParameters<typeof A>): T {
return new this(...args)
}
constructor(foo: number) {}
}
class B extends A {}
const b: B = B.instantiate(3) // Fine
class C extends A {
constructor(foo: number, bar: boolean) {
super(foo)
}
}
const c: C = C.instantiate(3) // Error: The 'this' context of type 'typeof C' is not assignable to method's 'this' of type 'new (foo: number) => A'.
此模式不会阻止重写
constructor
方法,但它可以再次保护父静态方法对子类的不当实例化。