TypeScript Generics
Generics & Constraints
Generics let you write code that works over many types while keeping full type safety. The type flows through, so the compiler knows exactly what comes out.
TypeScript 5
Interview Key
3 Topics
01
Generic Functions
A type parameter <T> is a placeholder the caller fills in (or the compiler infers). It preserves the relationship between input and output types instead of collapsing to any.
TypeScript — Generic Function
// T is inferred from the argument function identity<T>(x: T): T { return x; } const a = identity("hi"); // a: string const b = identity(42); // b: number // generic over an array — return type tracks the element type function first<T>(arr: T[]): T | undefined { return arr[0]; } const n = first([1, 2, 3]); // n: number | undefined // two type params function pair<A, B>(a: A, b: B): [A, B] { return [a, b]; } pair("x", 1); // [string, number]
Without generics, a reusable function would take
any and lose all type info on the return. <T> keeps the compiler's knowledge of the type intact from input to output.02
Constraints & Defaults
T extends X constrains the type parameter so you can safely use X's members inside. A default (T = X) supplies a fallback when the caller doesn't specify or the compiler can't infer.
TypeScript — extends & keyof
// constrain T to things that have a .length function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b; // .length is safe now } longest("abc", "de"); // OK — strings have length longest([1], [1, 2]); // OK — arrays too // K extends keyof T — type-safe property access function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } const user = { name: "Ada", age: 36 }; getProp(user, "name"); // string // getProp(user, "email"); // Error: "email" is not a key of user // default type parameter function makeBox<T = string>(v: T) { return { value: v }; }
K extends keyof T is one of the most useful generic patterns: it guarantees the key you pass actually exists on the object, and the return type T[K] is exactly that property's type.03
Generic Interfaces & Classes
TypeScript — Generic Interface & Class
// generic interface interface ApiResponse<T> { data: T; status: number; } const res: ApiResponse<string[]> = { data: ["a"], status: 200 }; // generic class — a type-safe stack class Stack<T> { private items: T[] = []; push(x: T): void { this.items.push(x); } pop(): T | undefined { return this.items.pop(); } } const s = new Stack<number>(); s.push(1); const top = s.pop(); // number | undefined — fully typed
✓
Quick Quiz
1. A type parameter <T> lets a function…
2. T extends { length: number } means…
3. K extends keyof T guarantees…
4. T[K] as a return type gives you…
5. T = string in a generic declaration is…