【问题标题】:Error when constraining a mixin input class to an interface将 mixin 输入类约束到接口时出错
【发布时间】:2022-01-16 13:33:02
【问题描述】:

我正在尝试制作一个 mixin 来给某些类一个接口约束,以便我知道输入类具有某些属性。

这是我目前拥有的。

  name: string;
  description: () => string;
}

function mixin<TBase extends Interface>(base: new(...args: any[]) => TBase) {
  return class Mixin extends base {
    get summary() {
      return `${this.name} ${this.description()}`;
    }
  }
}

我得到的错误是函数内部的 Mixin 类,错误是

  'Mixin' is assignable to the constraint of type 'TBase', but 'TBase' could be instantiated with a different subtype of constraint 'Interface'.ts(2415)

如何解决此错误?

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    你可以试试

    interface Interface{
       name: string;
      description: () => string;
    }
    type GConstructor<T extends Interface> = new (...args: any[]) => T;
    
    function mixin<TBase extends GConstructor<Interface>>(base: TBase) {
      return class Mixin extends base {
        get summary() {
          return `${this.name} ${this.description()}`;
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 2012-07-18
      • 2019-06-19
      • 2010-10-29
      • 1970-01-01
      相关资源
      最近更新 更多