【问题标题】:How to constraint type of abstract class in Typescript如何在 Typescript 中限制抽象类的类型
【发布时间】:2019-01-30 22:02:14
【问题描述】:

这就是我想做的:

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

基本上我希望 newDerived 仅从非抽象实现中调用。

但是,我在 extends this 部分收到此错误: “类型 'T' 不是构造函数类型。您的意思是让 T 被限制为类型 'new (...args: any[]) => AbBase'?”

但是如果我这样做了

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

它说,“基本构造函数返回类型'AbstractInstanceType'不是对象类型或对象类型与静态已知成员的交集。”

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以将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 
    

    【讨论】:

    • 这需要我在 A 中实现抽象成员,但我只想能够为那些已经实现所有抽象类型的人扩展“this”
    • 我也最终无法在 newDerived() 中引用“this”的静态成员
    • @NathanielTucker 我修复了重新实现抽象方法的要求,使用Pick 这并不理想,但由于构造函数返回一个抽象类型,编译器要求我们重新实现所有抽象方法。我不确定如何解决静态问题,如果我和任何约束条件编译器将不再让我们从this 派生。在 TS 中构建 mixins 的方式有点脆弱:github.com/Microsoft/TypeScript/pull/13743
    • @NathanielTucker 仅供参考我认为在 mixin 类中实现成员的要求是一个错误,我将其提交为:github.com/Microsoft/TypeScript/issues/29653
    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 2022-12-06
    • 1970-01-01
    • 2021-06-24
    • 2021-05-12
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    相关资源
    最近更新 更多