Mixin with a Generic Constraint not working

135 Views Asked by At

I was trying to create a mixin as follows -

class TestModel {
    name?: string;
}

type Constructor<T> = new (...args: any[]) => T;

function mixinA<T extends TestModel>(base: Constructor<T>): Constructor<T & {id?: string}>  {
    class Dummy extends base {
        id?: string;
    }
    return Dummy as Constructor<T & {id?: string}>;
}

This throws the following error -

Class 'Dummy' incorrectly extends base class 'T'.
  'Dummy' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'TestModel'.

Why the fact that T could be instantiated with a different subtype effect the Dummy extending a Class T, and even if it did, why does the code below work without any error -

function mixinA<T extends Constructor<TestModel>>(base: T): T & Constructor<{id?: string}>  {
    class Dummy extends base {
        id?: string;
    }
    return Dummy as T & Constructor<{id?: string}>;
}

It is the same code except the Generic Type extends the Constructor itself instead of the Object?

0

There are 0 best solutions below