【发布时间】:2021-11-17 02:58:28
【问题描述】:
我想创建一个 mixin,它可以使用混入它的类的方法。但是这不起作用。
////////////////////
// Simple class
class User {
sayHello(msg:string){
console.log(msg)
}
}
// Needed for all mixins
type Constructor<T = {}> = new (...args: any[]) => T;
////////////////////
// A mixin that adds a method that uses a base class method
function Activatable<TBase extends Constructor>(Base: TBase) {
return class extends Base {
activate() {
(Base as unknown as User).sayHello("activated")
}
};
}
////////////////////
// Using the composed class
////////////////////
const ActivableUser = Activatable(User)
const activableUser = new ActivableUser()
activableUser.activate()
运行失败并显示[ERR]: Base.sayHello is not a function 。
有什么方法可以创建一个可以访问基类方法和属性的 mixin?
【问题讨论】:
标签: typescript mixins