TypeScript Generic Classes
A generic class is a class that names a placeholder type for the values it holds. Each instance fixes the placeholder to one real type.
A generic interface
Box holds one value of type T. Each box fixes T to a different type.
interface Box<T> {
value: T;
}
const textBox: Box<string> = { value: "hello" };
const numBox: Box<number> = { value: 42 };
console.log(textBox.value);
console.log(numBox.value);A generic stack class
Stack stores items in a private array. pop returns the last item pushed in.
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
const stack = new Stack<number>();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.pop());
console.log(stack.pop());Example
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
size(): number {
return this.items.length;
}
}
const names = new Stack<string>();
names.push("ana");
names.push("ben");
names.push("cy");
console.log(names.pop());
console.log(names.size());Key points
- The placeholder is written inside angle brackets after the class name.
- Each instance fixes the placeholder to one real type.
- A generic interface names a shape with a placeholder type.
- Fields and methods use the placeholder as their type.
- The compiler checks every value against the fixed type.
In this example, Stack is created with string as its type. Three names are pushed onto the stack. pop removes the last name, and size reports the two names that remain.
Note
The placeholder is erased at runtime. The checks happen only during compilation.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
What does new Stack<string>() fix for that instance?