Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript Storing reference to a Generic class inside interface then creating an object from the class

Im trying to learn and understand Typescript Generics but I’m stuck with the following situation:

class A {
    helloworld() {
        console.log('hello world a')
    }
}

interface IConfig<T extends typeof A> {
    class: T
}

function testing<T extends typeof A>(config?: IConfig<T>) {
    if (config === undefined) {
        config = {class: A};
    }

    const thisClass = new config.class();
    thisClass.helloworld();
}

testing();

class B extends A {
    helloworld() {
        console.log('hello world b')
    }
}

testing({class: B})

Im getting this from WebStorm Type 'typeof A' is not assignable to type 'T'.   'typeof A' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'typeof A'.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need a minor tweak to your function:

function testing<T extends typeof A>(config?: IConfig<T | typeof A>) {
    const conf = config ?? { class: A }
    const thisClass = new conf.class();
    thisClass.helloworld();
}

Playground

You can’t in general have a default assignment with a generic like that, unless you explicitly include the default type along with the generic like I’ve included with IConfig<T | typeof A> otherwise the compiler will correctly complain that you haven’t covered all the possible T’s. Note this holds true even if your T extends your default type: T could still be a more complex superset of A.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading