How do you write a generic class in TypeScript, for example a Stack?
Put the type parameter after the class name, like class Stack<T>, and use T in fields and method signatures. Each instance fixes T when created, so new Stack<number>() only accepts and returns numbers.
Explain it simply
A stack of plates: it does not care whether the plates are steel or ceramic, but one stack should hold one kind. A generic class captures that. The class logic (push, pop) is written once, and each instance decides what it holds.
The compiler then stops you from pushing a string onto a stack of numbers, and pop() returns the right type without a cast.
Example
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
get size(): number {
return this.items.length;
}
}
const nums = new Stack<number>();
nums.push(10);
nums.push(20);
// nums.push("x"); // Error: string is not assignable to number
console.log(nums.pop()); // 20, typed number | undefined
const names = new Stack<string>(); // separate instance, separate TWhat to say in the interview
"A generic class declares its type parameter after the name and uses it in properties and methods. T is chosen per instance, so one Stack implementation serves numbers, strings or objects with full type checking. Static members cannot use the class's T."
Common mistakes
- Using T inside a static method; static members belong to the class, not an instance.