Generics in TypeScript Implementation Issue

Soumyadip Majumder 100 Reputation points
2025-04-18T09:06:16.2866667+00:00

There is an issue with the following TypeScript implementation of generics. The code is intended to define a generic interface for a data storage container, but it does not seem to work as expected. Here is the code:

// Define a generic interface for a data storage container
interface DataStorage<T> {
  addItem(item: T): void;
  getItems(): T[];
}

// Implement the generic interface
class Storage<T> implements DataStorage<T> {
  private items: T[] = [];

  addItem(item: T): void {
    this.items.push(item);
  }

  getItems(): T[] {
    return this.items;
  }
}

// Example usage with different types
const stringStorage = new Storage<string>();
stringStorage.addItem("TypeScript");
stringStorage.addItem("Generics");
console.log(stringStorage.getItems()); // Output: ["TypeScript", "Generics"]

const numberStorage = new Storage<number>();
numberStorage.addItem(42);
numberStorage.addItem(7);
console.log(numberStorage.getItems()); // Output: [42, 7]

const objectStorage = new Storage<{ name: string }>();
objectStorage.addItem({ name: "Ashutosh" });
objectStorage.addItem({ name: "Baban" });
console.log(objectStorage.getItems()); // Output: [{ name: "Ashutosh" }, { name: "Baban" }]

What could be the cause of the issue with this implementation?

Not Monitored
Not Monitored
Tag not monitored by Microsoft.
43,612 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.