如何在TypeScript中表达以下代码?
const enhanceClass = (cls) => {
cls.prototype.add = (a, b) => a + b;
}
class A {}
enhanceClass(A);
const i = new A()
i.add(1, 2);
答案 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)
尽管它的功能与您的示例不完全相同,但我认为对传入的类原型进行变异可能不是最佳实践。