这就是我想做的:
abstract class AbBase
static newDerived<T extends typeof AbBase>(this: T) {
return class A extends this {
//...
}
}
本质上,我希望 newDerived 仅从非抽象实现中调用。
但是,我在extends this
部分收到此错误:"类型'T'不是构造函数类型。您的意思是将 T 限制为键入"新(...args: any[]) => AbBase'?"
但是如果我这样做
static newDerived<T extends typeof AbBase>(this: new (...args: any[]) => AbstractInstanceType<T>) {
它说,"基构造函数返回类型'AbstractInstanceType'不是对象类型或对象类型与静态已知成员的交集。
您可以将T
限制为返回AbBase
的构造函数。这将解决非抽象类需求,并将满足编译器可以继承的要求:
abstract class AbBase {
static newDerived<T extends { new (...a: any[]) : Pick<AbBase, keyof AbBase> } >(this: T) {
return class A extends this {
}
}
}
AbBase.newDerived() // error
class Derived extends AbBase {}
Derived.newDerived() // ok