【发布时间】:2021-09-21 22:34:07
【问题描述】:
我有以下代码:
class Entity {
id: number
}
class ChildEntity extends Entity {
child_property: number;
}
class ChildEntity2 extends Entity {
child_property_2: number;
}
class Data<T extends Entity> {
protected entity: T
static method() {
}
}
class ChildData extends Data<ChildEntity> {
childMethod() {
this.entity.child_property = 1;
}
}
class ChildData2 extends Data<ChildEntity2> {
childMethod() {
this.entity.child_property_2 = 1;
}
}
function doStuffAndInstantiate(Input /* What should be the type here??? */ ) {
// function doStuffAndInstantiate<T extends Entity>(Input: new ()=> Data<T> ) { /* Error at Input.method() call: Property 'method' does not exist on type 'new () => Data '. */
// function doStuffAndInstantiate(Input: typeof Data ) { /* error at doStuffAndInstantiate(ChildData) call: 'ChildEntity' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Entity'. */
Input.method();
return new Data();
}
doStuffAndInstantiate(ChildData);
doStuffAndInstantiate(ChildData2);
doStuffAndInstantiate 的 Input 参数的类型应该是什么?我尝试了很多方法都没有成功:(
【问题讨论】:
标签: typescript typescript-generics