Cheat Sheet
The commands you keep forgetting, with a one-line description and a real example you can copy - 629 across 38 tools. Pick a tool in the sidebar, or search across all of them.
Showing TypeScript. Choose another tool in the sidebar, or search all 629 commands.
TypeScript
Types, narrowing, generics, and the utility types worth memorizing.
| Command | What it does | Example |
|---|---|---|
basic annotations | Types on variables, params, and returns. | function total(items: number[]): number { return items.length } |
interface | Name an object shape. | interface User { id: number; name: string } |
type alias | Name any type - unions included. | type Status = 'draft' | 'sent' | 'paid' |
optional ? | Property may be missing. | interface Opts { retries?: number } |
readonly | Property cannot be reassigned. | interface Cfg { readonly apiUrl: string } |
union | | One of several types. | let id: string | number |
narrowing: typeof | Branch by primitive type - TS follows. | if (typeof id === 'string') id.toUpperCase() |
narrowing: in | Branch by property presence. | if ('error' in result) console.log(result.error) |
narrowing: instanceof | Branch by class. | if (e instanceof TypeError) retry() |
discriminated union | A shared literal field makes switches exhaustive. | type Shape = { kind: 'circle'; r: number } | { kind: 'rect'; w: number; h: number } |
generics | A type parameter flows in and out. | function first<T>(arr: T[]): T | undefined { return arr[0] } |
generic constraint | Require a capability of T. | function byId<T extends { id: number }>(items: T[], id: number) { return items.find(i => i.id === id) } |
Partial<T> | All properties optional - update payloads. | function patch(u: Partial<User>) {} |
Pick<T, K> | Keep only the listed keys. | type Preview = Pick<User, 'id' | 'name'> |
Omit<T, K> | Everything except the listed keys. | type NewUser = Omit<User, 'id'> |
Record<K, V> | Object with known key and value types. | const stock: Record<string, number> = { kettle: 4 } |
Required<T> / Readonly<T> | Make everything required / immutable. | type Frozen = Readonly<Config> |
ReturnType<typeof fn> | The type a function returns. | type Row = ReturnType<typeof parseRow> |
keyof | The property names of a type, as a union. | type UserField = keyof User |
as const | Freeze literals into exact types. | const ROLES = ['admin', 'editor'] as const |
satisfies | Check against a type without widening to it. | const theme = { bg: "#fff" } satisfies Record<string, string> |
unknown (not any) | Safe top type - must narrow before use. | function parse(x: unknown) { if (typeof x === "string") return x.trim() } |