如何在Typescript中动态扩展泛型类(向其添加属性)作为参数?

时间:2018-07-10 00:53:19

标签: typescript

如何在TypeScript中表达以下代码?

const enhanceClass = (cls) => {
  cls.prototype.add = (a, b) => a + b;
}
class A {}
enhanceClass(A);
const i = new A()
i.add(1, 2);

1 个答案:

答案 0 :(得分:3)

TypeScript added support for mixin classes in 2.2.尝试以下操作:

type Constructor<T = {}> = new (...args: any[]) => T

function enhanced<T extends Constructor>(Base: T) {
  class WithAdd extends Base {
    add(a: number, b: number) {
      return a + b
    }
  }

  return WithAdd
}

const EnhancedA = enhanced(class A {})

const a = new EnhancedA()
a.add(1, 2)

尽管它的功能与您的示例不完全相同,但我认为对传入的类原型进行变异可能不是最佳实践。