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):
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");
}
}