laprof
laprof

Reputation: 1344

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. 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>;
}

Upvotes: 1

Views: 750

Answers (1)

Istvan Szasz
Istvan Szasz

Reputation: 1567

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.
  }
}

Upvotes: 2

Related Questions