What are generics in TypeScript?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for TypeScript development. It reveals whether you understand the building blocks that more complex concepts rely on.
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.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex TypeScript answers easy to follow.