如何在打字稿中约束抽象类的类型



这就是我想做的:

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 

最新更新