Advanced TypeScript: Generics and Utility Types
Generics make functions and types reusable without sacrificing type safety. Utility types transform existing types-essential for API layers and form handling.
Generic Functions
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const n = first([1, 2, 3]); // number | undefined
const s = first(['a', 'b']); // string | undefined
Constrained Generics
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Utility Types
Partial<T>- all properties optionalPick<T, K>- subset of keysOmit<T, K>- exclude keysRecord<K, V>- keyed object type
type UpdateUserDto = Partial<Pick<User, 'name' | 'email'>>;
Conclusion
Master generics and utilities before reaching for complex conditional types. They keep DTOs, reducers, and hook return types DRY and accurate.