Generics let you write reusable functions, classes and types that work with many types while keeping full type safety. Instead of using any (which turns off type checking), you use a type parameter that is filled in when the code is used. Without generics function firstItem(items: any[]): any { return items[0]; } const n = firstItem([1, 2, 3]); // n is any — type information lost With generics function firstItem<T>(items: T[]): T | undefined { return items[0]; } const n = firstItem([1, 2, 3]); // number | undefined (inferred) const s = firstItem(['a', 'b']); // string | undefined Generic interfaces and types interface ApiResponse<T> { data: T; status: number; errors?: string[]; } async function getJson<T>(url: string): Promise<ApiResponse<T>> { const res = await fetch(url); return { data: (await res.json()) as T, status: res.status }; } const users = await getJson<User[]>('/api/users'); users.data[0].name; // fully typed (Remember: the cast does not validate data at runtime; for untrusted responses, validate with a schema library such as zod.) Generic classes class Repository<T extends { id: string }> { private items = new Map<string, T>(); save(item: T) { this.items.set(item.id, item); } find(id: string): T | undefined { return this.items.get(id); } } const products = new Repository<Product>(); Constraints with extends function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } getProperty({ name: 'Asha', age: 30 }, 'name'); // string getProperty({ name: 'Asha', age: 30 }, 'salary'); // compile error: not a key function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b; } Default type parameters interface PagedResult<T, TCursor = string> { items: T[]; nextCursor: TCursor | null; } Generics in everyday code - Built-in types: Array<T>, Promise<T>, Map<K, V>, Set<T>, Record<K, V>. - React: useState<User | null>(null), components with generic props (a generic Table<T> component). - Angular: HttpClient.get<Order[]>(url), EventEmitter<T>, signal<T>(). - Utility types like Partial<T>, Pick<T, K> and ReturnType<F> are generic types. Why they are useful - Type safety without duplication: one implementation, many types. - Better autocomplete and refactoring. - Expressing relationships between inputs and outputs (the return type depends on the argument type). - Building flexible, reusable libraries and components. Tips - Let TypeScript infer type arguments when possible. - Do not add type parameters that are used only once; they add complexity without benefit. - Use constraints to describe the minimum capabilities required. Interview summary: "Generics are type parameters that make functions, classes and types reusable across types while preserving type information — like Array<T> or Promise<T>. Constraints (extends) restrict what types are allowed, and keyof enables safe property access patterns."
Ravindra Wadile · · 0 likes