可以从泛型类型创建实例吗?

huangapple go评论61阅读模式
英文:

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&lt;T extends Entity&gt; {
    create() {
        const instance = new T(&quot;theValue&quot;);  // ERROR: &#39;T&#39; 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&lt;T extends new (someValue: string) =&gt; Entity&gt; {
    create() {
        const instance = new T(&quot;theValue&quot;);  // ERROR: &#39;T&#39; 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&lt;T extends Entity&gt; {
    create(entityConstructor: new(v:string)=&gt;T) {
        const instance = new entityConstructor(&quot;theValue&quot;); 
    }
    
    owned: new(v:string)=&gt;T
    constructor(owned:new(v:string)=&gt;T){this.owned = owned}
    createOwned() {
        const instance = new this.owned(&quot;theValue&quot;); 
    }
}

huangapple
  • 本文由 发表于 2023年3月31日 21:05:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定