如何在 TypeScript 中混入给定的 SuperClass 之前正确地注入方法或属性的类型

问题描述

在下面的例子中,在通过参数作为超类传递给mixin函数的类中没有正确找到方法的类型:

type Constructor = new (...args: any[]) => {};

function ClassMixin<TBase extends Constructor>(Base: TBase) {
    return class extends Base {
        method() {
            console.log("method method method method");
        }
    }
}

const MyClass = ClassMixin(class Z {
    constructor() {
        this.method(); // NOT OK: Property 'method' does not exist on type 'Z'
    }
});

const z = new MyClass();

z.method(); // <---- ok

playground example


我找到了一种解决方法来使其工作,但我正在寻找一种更“自动化”的解决方案,请查看下面的解决方法

type Constructor = new (...args: any[]) => {};

function ClassMixin<TBase extends Constructor>(Base: TBase) {
    return class extends Base {
        method() {
            console.log("method method method method");
        }
    }
}

interface ClassMixinInterface {
    method(): void
}

interface Z extends ClassMixinInterface { }

class Z {
    constructor() {
        this.method(); // <---- ok
    }
}

const MyClass = ClassMixin(Z);

const z = new MyClass();

z.method(); // <---- ok

playground work-around example

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)