小编Kii*_*age的帖子

TypeScript中的类型安全的mixin装饰器

我试着定义类型安全的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)

generics decorator mixins typescript

8
推荐指数
1
解决办法
1834
查看次数

标签 统计

decorator ×1

generics ×1

mixins ×1

typescript ×1