简体   繁体   English

如何在Typescript中约束抽象类的类型

[英]How to constraint type of abstract class in Typescript

This is what I want to do:这就是我想要做的:

abstract class AbBase
  static newDerived<T extends typeof AbBase>(this: T) {
    return class A extends this {
      //...
    }
  }

Essentially I want newDerived to only be called from non-abstract implementations.本质上,我希望 newDerived 只能从非抽象实现中调用。

However, I get this error on the extends this part: "Type 'T' is not a constructor function type. Did you mean for T to be constrained to type 'new (...args: any[]) => AbBase'?"但是,我在extends this部分时收到此错误:“类型 'T' 不是构造函数类型。您的意思是将 T 限制为类型 'new (...args: any[]) => AbBase' ?”

But then if I do但是如果我这样做

  static newDerived<T extends typeof AbBase>(this: new (...args: any[]) => AbstractInstanceType<T>) {

it says, "Base constructor return type 'AbstractInstanceType' is not an object type or intersection of object types with statically known members."它说,“基本构造函数返回类型‘AbstractInstanceType’不是对象类型或对象类型与静态已知成员的交集。”

You can constrain T to be a constructor that returns AbBase .您可以将T约束为返回AbBase的构造AbBase This will solve both the non-abstract class requirement and will satisfy the compiler that this can be inherited:这将解决非抽象类的要求,并使编译器可以继承它:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM