Generics are type parameters: function identity<T>(x: T): T stays accurate for every caller. Constrain with T extends { id: number }, give defaults (T = string), and use infer in conditional types for libraries. Start with generic functions before you write clever mapped types.
This TypeScript cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- Param:
<T>on functions, types, classes. Infer from arguments when you can. - Constraint:
T extends { id: string }so you may readid. - Default:
type Box<T = unknown> = { value: T }. - Multiple:
Kfor keys,Vfor values:Map<K, V>. - keyof:
function pick<T, K extends keyof T>(obj: T, key: K): T[K]. - infer:
T extends Promise<infer U> ? U : Tunwraps promises. - Limits: Error messages get loud. If a generic is only used once, a concrete type is clearer.
- JSX: Arrow generics need a trailing comma or
extends:<T,>(x: T)in.tsx.
Copy-paste examples
pick helper and a constrained list
The return type T[K] stays in sync with the key you passed.
export function pick<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
export function byId<T extends { id: number }>(rows: T[], id: number): T | undefined {
return rows.find((row) => row.id === id);
}
export type Awaited<T> = T extends Promise<infer U> ? U : T;Common mistakes
- Inventing
<T = any>so the generic does nothing. - Five type parameters on a UI component nobody can call without copying an example.
- Forgetting
.tsxgeneric comma and fighting a JSX parse error. - Using generics to avoid modeling the actual API union you received.
FAQ
- When should I not use a generic? When there is only one type ever.
Useris better thanTif T is always User.
- Generic vs BLOGPH0 ?
unknownis one type you must narrow. A generic stays specific at each call site without losing fields.
- Can I generic a React component? Yes:
function List<T>({ items }: { items: T[] }). InferTfromitems.
Related TypeScript cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.