how to properly inject type of an method or property to before mixin a given SuperClass in TypeScript

Viewed 260

In the example below, the type of method is not properly found in the class passed by parameter as superclass to the mixin function:

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


I found a work-around to make it work, but I'm searching for a more 'automatic' solution, check the work-around below:

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

0 Answers
Related