Tech
TypeScript Generics Without Fear
cover image
Generics feel intimidating, but in the end they’re just “a tool for handling types like values.” Learn five common patterns and most situations get comfortable.
1. Get the feel with the identity function
function identity<T>(value: T): T {
return value;
}
T is a blank that the caller fills in. Once that intuition clicks, everything else is application.
2. Adding constraints (extends)
function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Pin down that K must be a key of T, and typos get caught at compile time.
3–5. Defaults, conditional types, utilities
Defaults (<T = string>), conditional types (T extends U ? X : Y), and utility types like Partial and Pick. This combination safely expresses most production code.
Generics are documentation for future-you. The types become the manual.
Comments
No comments yet. Be the first to write one.