英文:
Is it possible to create an instance from a generic type?
问题
我有一个名为Entity的类,如下所示:
class Entity {
constructor(readonly someValue: string) {}
someFunction() {}
}
现在,我想创建一个管理这些实体的类,能够创建它们的实例。由于我可能会派生这些实体,要使用的实体类应该是一个泛型类参数,如下所示:
class Manager1<T extends Entity> {
create() {
const instance = new T("theValue"); // 错误:'T'只是一个类型,但在此处被用作值。
}
}
这会导致上述错误。或者,我尝试了以下方法(也不起作用):
class Manager2<T extends new (someValue: string) => Entity> {
create() {
const instance = new T("theValue"); // 错误:'T'只是一个类型,但在此处被用作值。
}
}
是否有一种方法可以在类内部构造Entity实例,只给定类型作为泛型参数(以某种方式强制指定类型的构造函数必须与指定的签名匹配)?
英文:
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) ?
答案1
得分: 2
你无法创建一个可以想象的东西
你必须提供真实的(即运行时的)东西给它
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");
}
}
英文:
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");
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论