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

Is it possible to create an instance from a generic type?

I have a class called Entity like so:

class Entity {
    constructor(readonly someValue: string) {}
    someFunction() {}
}

Now I want to create a class which manages these entities, being able to create instances of them. Since I might potentially derive those entities, the entity class to be used should be a generic class argument like so:

class Manager1<T extends Entity> {
    create() {
        const instance = new T("theValue");  // ERROR: 'T' only refers to a type, but is being used as a value here.
    }
}

This causes the stated error. Alternatively I tried this (which doesn’t work either):

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

class Manager2<T extends new (someValue: string) => Entity> {
    create() {
        const instance = new T("theValue");  // ERROR: 'T' only refers to a type, but is being used as a value here.
    }
}

Is there a way to construct the Entity instance inside the class, given only the TYPE as a generic argument (somehow enforcing that the ctor of that type must match the specified signature) ?

>Solution :

You can’t create an imaginable thing
You have to provide the real(i.e. runtime) thing to it

class Manager1<T extends Entity> {
    create(entityConstructor: new(v:string)=>T) {
        const instance = new entityConstructor("theValue"); 
    }
    
    owned: new(v:string)=>T
    constructor(owned:new(v:string)=>T){this.owned = owned}
    createOwned() {
        const instance = new this.owned("theValue"); 
    }
}
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