Not Monitored
Tag not monitored by Microsoft.
43,612 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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?