[英]TypeScript map with generic abstract object
I have several Items that they all inherit from the abstract Item.我有几个项目,它们都继承自抽象项目。 The object should contain a map with different Item implementations.
object 应包含具有不同项目实现的 map。 With my current code I encountered the following error in the Object:
使用我当前的代码,我在 Object 中遇到以下错误:
TS2314: Generic type 'Item<'T'>' requires 1 type argument(s)
TS2314:通用类型 'Item<'T'>' 需要 1 个类型参数
In Java, that's not a problem.在 Java 中,这不是问题。 How do I get this to work in TypeScript?
如何让它在 TypeScript 中工作?
Items项目
abstract class Item<T> {
}
class Item1 extends Item<boolean> {
}
class Item2 extends Item<number> {
}
Object.ts Object.ts
class Object {
private itemMap: Map<number, Item>;
}
Try this:尝试这个:
class Object {
private itemMap: Map<number, Item1 | Item2>;
}
If you plan to add new classes extending Item
and support those in Object
, you could use Item<any>
.如果您计划添加扩展
Item
的新类并支持Object
中的类,则可以使用Item<any>
。
It would work for all the generic types for which a derived Item
class exists;它适用于存在派生
Item
class 的所有泛型类型; and you couldn't instantiate objects with generic types for which you haven't declared a derived class:并且您无法使用尚未声明派生 class 的泛型类型实例化对象:
class Object {
private itemMap: Map<number, Item<any>>;
public constructor() {
this.itemMap = new Map();
this.itemMap.set(1, new Item1()); // ok
this.itemMap.set(2, new Item2()); // ok
this.itemMap.set(3, new Item<string>()); // Error: Cannot create an instance of an abstract class.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.