Reusable Data Structures
You'll learn how to write custom data structures like stacks, queues, and trees that work with any element type using generics.
Why Build Generic Data Structures?
Without generics, you'd need a separate NumberStack, StringStack, UserStack, etc. — or resort to any, losing type safety. Generics let you write one implementation that works for all types while preserving compile-time checks.
Think of it like a universal container mold: the same structure can hold marbles, coins, or candies — you just specify what goes inside.
Writing a Generic Stack
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
get size(): number {
return this.items.length;
}
}
// Type-safe usage
const numberStack = new Stack<number>();
numberStack.push(10);
numberStack.push(20);
const top = numberStack.pop(); // type: number | undefined
const stringStack = new Stack<string>();
stringStack.push("hello");
// stringStack.push(42); // ❌ Error: number not assignable to string
The type parameter T flows through every method, ensuring all operations respect the element type you choose.
Other Generic Structures
You can apply the same pattern to queues (first-in-first-out), linked lists, binary trees, or any custom container:
class Queue<T> {
private items: T[] = [];
enqueue(item: T): void {
this.items.push(item);
}
dequeue(): T | undefined {
return this.items.shift();
}
}
Key Takeaway: Generic data structures let you write reusable, type-safe containers once and instantiate them with any element type, eliminating duplication while maintaining compile-time guarantees.