What are generics and why are they useful in TypeScript?
Generics are type parameters that let you write reusable code that works with multiple types without sacrificing type safety.
// Without generics — must duplicate or use any
function getFirstAny(arr: any[]): any { return arr[0]; }
// With generics — type-safe and reusable
function getFirst<T>(arr: T[]): T { return arr[0]; }
const n = getFirst([1, 2, 3]); // T inferred as number
const s = getFirst(['a', 'b']); // T inferred as string
// n and s have correct types — no runtime casting needed
Generic interfaces and types:
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
type UserResponse = ApiResponse<User>;
type ListResponse = ApiResponse<User[]>;
// Generic class
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]; }
}
const numStack = new Stack<number>();
numStack.push(1);
numStack.push('a'); // ❌ Error — string not assignable to number