What are generics in TypeScript?

Answer

Generics allow you to write reusable code that works with a variety of types while maintaining full type safety. Instead of using any, you use a type parameter (a placeholder for a specific type). Syntax: function identity<T>(arg: T): T { return arg; }T is the type parameter. When you call identity("hello"), TypeScript infers T = string, and the return type is string. You can explicitly specify: identity<number>(42). Generic interfaces: interface Box<T> { value: T; }. Generic classes: class Stack<T> { private items: T[] = []; push(item: T): void { ... } }. You can have multiple type parameters: function pair<K, V>(key: K, value: V): [K, V] { return [key, value]; }. Generics are the foundation of TypeScript's type system — they power all utility types (Array, Promise, Map, Set, etc.) and enable writing type-safe libraries.