简体   繁体   English

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

[英]How to dynamically extend (add properties to) generic class as argument in Typescript?

How to express the following code in TypeScript? 如何在TypeScript中表达以下代码?

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

TypeScript added support for mixin classes in 2.2. TypeScript在2.2中添加了对mixin类的支持。 Try this: 尝试这个:

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)

Though it doesn't do the exact same as in your example, I'd argue that mutating the class prototype being passed in is probably not the best practice anyway. 尽管它与您的示例不完全相同,但是我认为对传入的类原型进行变异可能不是最佳实践。

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

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