【发布时间】:2018-02-14 19:11:38
【问题描述】:
我有一个案例,我需要在不同类别的项目之间获取层次结构。它们都扩展了同一个类 ItemExt。
我正在使用 Typescript 2.4.2
这是我的代码:
export class ItemCollection<ItemFather extends ItemExt, ItemSon extends ItemExt> {
constructor(private typeClass: { new (): ItemSon; }, parent? : ItemFather, fatherColl? : ItemCollection<ItemFather, ItemSon>){
}
public GetSub<ItemSon extends ItemExt, ItemSub extends ItemExt>(typeClass: { new (): ItemSub; }, obj : ItemSon) {
return new ItemCollection<ItemSon, ItemSub>(typeClass, obj, this);
}
}
export abstract class ItemExt {
public Id : string;
}
但是编译器在“this”的方法“GetSub”中给我一个错误:
“this”类型的参数不能分配给类型参数 '项目集合'。类型“ItemCollection”不可分配给类型“ItemCollection”。类型“ItemFather”不可分配给类型“ItemSon”。类型 'ItemExt' 不可分配给类型 'ItemSon'。
我认为这只是语法或声明问题,因为当我使用 eval("this") insted of "this" 时,它按预期工作。
有人可以帮我避免没有 eval 的编译错误吗?
提前致谢
【问题讨论】:
-
请不要将事物命名为
type。不要像有棱有角的那样迷惑很多人
标签: typescript generics compilation