Roadmap › TypeScript — Types, Generics and Real-World Patterns › Module: Classes and Generics
Lessons in this course (9)
5. Generics
Intermediate★ Must knowLesson 5 of 9
typescript
function first<T>(items: T[]): T | undefined { return items[0]; }
const n = first([1, 2, 3]); // T inferred as number
interface ApiResult<T> { data: T; error?: string; }
interface Paged<T> { items: T[]; total: number; page: number; }
// Constraint: T must have an id
function byId<T extends { id: number }>(items: T[], id: number): T | undefined {
return items.find(i => i.id === id);
}
// keyof constraint: safe property access
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map(i => i[key]);
}
pluck(orders, "status"); // OrderStatus[] — "statuz" would be a compile error
// Generic class
class Cache<K, V> {
private map = new Map<K, V>();
get(key: K) { return this.map.get(key); }
set(key: K, value: V) { this.map.set(key, value); }
}Generics let one function/type work with many types while keeping type information — unlike any, which loses it.