I'm currently trying to define a generic type for my mixin method that utilizes "extending class creating functions". However, I'm struggling with finding the correct syntax to implement it.
After researching, I came across an implementation in this answer
To illustrate, here's a brief and straightforward example:
// Defining the type for "extending class creating functions"
type Mixable<A extends any[], R> = (
ctor: new (...args: any[]) => any
) => abstract new (...args: A) => R;
type MixinFunction = {
<A1 extends any[], R1>(ctor1: Mixable<A1, R1>): new (...args: any) => R1;
<A1 extends any[], R1, A2 extends any[], R2>
(ctor1: Mixable<A1, R1>, ctor2: Mixable<A2, R2>): new (...args: any) => R1 & R2;
}
const Mixin: MixinFunction = ((_a: Mixable<any[], any>) => {
// Example content
return class {} as (new (...args: any[]) => any);
});
const Base = (superclass: Newable) => class _Base extends superclass {
foo():number {
return 1;
}
};
const Base2 = <T>(superclass: Newable) => class _Base2 extends superclass {
bar():T {
return 1 as T;
}
};
// Attempting to create a class using mixins results in ts(2562) error
class Derived<T> extends Mixin(Base, Base2) {
}
class DerivedString extends Derived<string> {}
(new Derived()).foo(); // Inferred as "number"
(new DerivedString()).bar(); // Desired return type inference is "string"