我试着定义类型安全的mixin()装饰函数,如下所示,
type Constructor<T> = new(...args: any[]) => T;
function mixin<T>(MixIn: Constructor<T>) {
return function decorator<U>(Base: Constructor<U>) : Constructor<T & U> {
Object.getOwnPropertyNames(MixIn.prototype).forEach(name => {
Base.prototype[name] = MixIn.prototype[name];
});
return Base as Constructor<T & U>;
}
}
Run Code Online (Sandbox Code Playgroud)
并使用如下,
class MixInClass {
mixinMethod() {console.log('mixin method is called')}
}
/**
* apply mixin(MixInClass) implicitly (use decorator syntax)
*/
@mixin(MixInClass)
class Base1 {
baseMethod1() { }
}
const m1 = new Base1();
m1.baseMethod1();
m1.mixinMethod(); // error TS2339: Property 'mixinMethod' does not exist …Run Code Online (Sandbox Code Playgroud)