I have several Items that they all inherit from the abstract Item. The object should contain a map with different Item implementations. With my current code I encountered the following error in the Object:
TS2314: Generic type 'Item<'T'>' requires 1 type argument(s)
In Java, that's not a problem. How do I get this to work in TypeScript?
Items
abstract class Item<T> {
}
class Item1 extends Item<boolean> {
}
class Item2 extends Item<number> {
}
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>
.
It would work for all the generic types for which a derived Item
class exists; and you couldn't instantiate objects with generic types for which you haven't declared a derived 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.
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.