Sub topic 5
Generic Classes
This chapter assumes you know basic TypeScript types, interfaces, type aliases, functions, union types, and class syntax. A generic class is a class that receives a type parameter. The parameter lets each instance work with a specific type while keeping type checking.
Why Use a Generic Class?
Suppose you need a stack. A stack stores values in last-in, first-out order. Without generics, you might store values as any. That allows every type, but it removes useful checks.
A generic stack stores one chosen type:
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 numbers = new Stack<number>();
numbers.push(10);
numbers.push(20);
const topNumber = numbers.pop(); // number | undefined
const names = new Stack<string>();
names.push("Ada");
names.push("Grace");
const topName = names.pop(); // string | undefined
// numbers.push("twenty"); // Error: string is not assignable to numberHere, T is a type parameter. It acts as a placeholder while the class is declared. Stack<number> replaces T with number for the numbers instance. Stack<string> replaces it with string for the names instance.
The pop method returns T | undefined because the stack may be empty. The generic type is preserved in that result.
How the Type Flows Through a Class
The type parameter belongs to each instance. It connects the fields, parameters, and return types that use it.
flowchart TD
A["Stack<T> class"] --> B["Stack<number>"]
A --> C["Stack<string>"]
B --> D["items: number[]"]
B --> E["push(number) and pop(): number | undefined"]
C --> F["items: string[]"]
C --> G["push(string) and pop(): string | undefined"]The class definition describes a pattern. The type argument supplied when creating an instance determines the pattern's concrete types.
Supplying Type Arguments
You will usually provide the type argument when calling new:
class Box<T> {
constructor(public value: T) {}
getValue(): T {
return this.value;
}
}
const countBox = new Box<number>(42);
const messageBox = new Box<string>("ready");
console.log(countBox.getValue()); // 42
console.log(messageBox.getValue()); // readyTypeScript can sometimes infer the type argument from constructor arguments:
const inferredBox = new Box(true);
// inferredBox has type Box<boolean>Explicit type arguments are useful when you want to document the intended type or when inference does not produce the type you need.
Generic Classes and Constraints
A class can restrict its type parameter with extends. This means the type must satisfy a required shape.
class Queue<T extends { id: number }> {
private items: T[] = [];
enqueue(item: T): void {
this.items.push(item);
}
dequeue(): T | undefined {
return this.items.shift();
}
}
const users = new Queue<{ id: number; name: string }>();
users.enqueue({ id: 1, name: "Ada" });
// users.enqueue({ name: "Grace" }); // Error: id is requiredThe constraint allows the class to rely on item.id safely, because every valid T must contain a numeric id.
Exercise
What is the type of result in const result = new Stack<boolean>().pop()?
Show answer
boolean | undefined, because the stack stores booleans and pop can return no value when the stack is empty.