首先,我对 TypeScript 很陌生,所以如果这是一个愚蠢的问题,我深表歉意。
我正在尝试创建一个可以通过附加功能进行扩展的基类。我尝试使用继承,但后来我意识到你不能扩展多个类。我的下一个尝试是使用装饰器,这似乎工作正常,但 TypeScript 没有为我提供装饰器方法的代码完成。
function Talks<T extends {new(...args:any[]):{}}>(constructor:T) {
return class extends constructor {
sayHello(): void {
console.log('Hello');
}
}
}
function Walks<T extends {new(...args:any[]):{}}>(constructor:T) {
return class extends constructor {
move(): void {
console.log('Walk');
}
}
}
function Chargeable<T extends {new(...args:any[]):{}}>(constructor:T) {
return class extends constructor {
chargeBattery(): void {
console.log('Charging');
}
}
}
@Talks
@Walks
@Chargeable
class Robot { }
@Chargeable
class Calculator { }
const robot = new Robot();
robot.sayHello();
robot.move();
robot.chargeBattery();
const calculator = …Run Code Online (Sandbox Code Playgroud)