1

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

1 Answer 1

2

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.
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'll try this later, but it seems to be not clean, because if I create new item classes, there are multiple spots where I have to change code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.