Struggling to determine the type of a typescript mixin class without using a workaround method. Here are a couple of examples:
type Constructor<T = {}> = new(...args: any[]) => T;
function MyMixin<T extends Constructor>(BaseClass: T) {
return class extends BaseClass {doY() {}}
}
// Option A: Clumsy and inefficient
const MixedA = MyMixin(class {doX() {}});
const dummy = new MixedA();
type MixedA = typeof dummy;
class OtherA {
field: MixedA = new MixedA();
a() {this.field.doX(); this.field.doY();}
}
// Option B: Lengthy
class Cls {doX() {}}
interface MixinInterface {doY(): void}
const MixedB = MyMixin(Cls);
type MixedB = Cls & MixinInterface;
class OtherB {
field: MixedB = new MixedB();
a() {this.field.doX(); this.field.doY();}
}
It's disappointing that TypeScript lacks proper support for mixins/traits. Is there an alternative way to define the type of field
without using typeof on an instance or duplicating signatures in an interface? I attempted typeof(new MixedBaseA())
, but typeof does not accept arbitrary expressions.