I'm trying to make a mixin to give some classes an interface constraint, so that I know that the input class has certain properties.
Here's what I have at the moment.
name: string;
description: () => string;
}
function mixin<TBase extends Interface>(base: new(...args: any[]) => TBase) {
return class Mixin extends base {
get summary() {
return `${this.name} ${this.description()}`;
}
}
}
The error I'm getting is at class Mixin inside the function, and the error is
'Mixin' is assignable to the constraint of type 'TBase', but 'TBase' could be instantiated with a different subtype of constraint 'Interface'.ts(2415)
How do I get around this error?
CodePudding user response:
You can try
interface Interface{
name: string;
description: () => string;
}
type GConstructor<T extends Interface> = new (...args: any[]) => T;
function mixin<TBase extends GConstructor<Interface>>(base: TBase) {
return class Mixin extends base {
get summary() {
return `${this.name} ${this.description()}`;
}
}
}