Open
Description
TypeScript Version: 2.6.0 and more
Search Terms: mixin, 2.6.
Code
export interface Constructor<T = any> extends Function {
new(...args: any[]): T;
}
class A<T> {
public a: T;
}
class B<T> {
public b: T;
}
function Mixin<T>(...classes: any[]): Constructor<T> {
return function() {
// whatever, not the purpose of the demonstration
} as any;
}
interface IAB<T, U> extends A<T>, B<U> {}
// on typescript 2.6.0 and more, its no more possible to use generic types into mixins....
class AB<T, U> extends Mixin<IAB<T, U>>(A, B) {
}
// on typescript 2.6.0 we're forced to write
// class AB<T, U> extends Mixin<IAB<any, any>>(A, B) {}
// so we loose type checking...
// intentional type error
class testClass extends AB<boolean, string> {
public a: number; // before 2.6.0 => type of 'a' properly detected as wrong, boolean expected
}
Expected behavior:
Like before typescript 2.6.0, extending a class with a mixin which takes generic types should be allowed.
Using mixin is a really common usage in js/ts to build classes which implement/inherit properties from more than one classe (sometimes named 'factories'). Before 2.6.0, typescript properly detected the union of class having generic types, but currently this generates TS2562 errors, so its no more possible to construct typed generic mixins.
In a more generic way:
function A<T>() {
return class {};
}
// should be allowed
class B<T> extends A<T>() {}
Actual behavior:
TS2562, Base class expression cannot reference class type parameters (on T and U)
Playground Link: here
Related Issues: Partially related #19668