TypeScript Cheat Sheet
Free TypeScript cheat sheet: basic types, interfaces, generics, narrowing, and must-know utility types at a glance.
Basic Types
| Concept | Syntax | Example |
|---|---|---|
| Primitives Annotate with a colon. TypeScript also infers types from values. | string, number, boolean | let age: number = 25; |
| Arrays Both forms are identical — type[] is more common. | type[] or Array<type> | const ids: number[] = [1, 2, 3]; |
| Union types A value that can be one of several types. | A | B | let id: string | number; |
| Literal types Restrict a value to exact strings/numbers — great for options. | "a" | "b" | type Size = "sm" | "md" | "lg"; |
| any vs unknown Prefer unknown: it forces you to check the type before using it. | any (off switch), unknown (safe) | const x: unknown = parse(data); |
Objects & Interfaces
| Concept | Syntax | Example |
|---|---|---|
| Interface Describes an object's shape. Interfaces can be extended. | interface Name { prop: type } | interface User { id: number; name: string } |
| Optional property The property may be missing — its type becomes type | undefined. | prop?: type | interface User { nickname?: string } |
| Type alias Names any type, including unions — interfaces only do object shapes. | type Name = ... | type ID = string | number; |
| Readonly Compile-time protection against reassignment. | readonly prop: type | interface Cfg { readonly url: string } |
| Extending Builds a new shape on top of an existing one. | interface B extends A {} | interface Admin extends User { role: string } |
Functions & Generics
| Concept | Syntax | Example |
|---|---|---|
| Function types Parameter and return types in one annotation. | (a: T) => R | const fn: (n: number) => string = String; |
| Default + optional params Optional params must come after required ones. | (a = 1, b?: string) | function greet(name = "world") {} |
| Generics Type-safe reuse — the type flows from the call site. | function f<T>(x: T): T | function first<T>(arr: T[]): T { return arr[0]; } |
| Generic constraint Limits which types a generic accepts. | <T extends Shape> | function len<T extends { length: number }>(x: T) {} |
| Type narrowing Inside the check, TypeScript knows the narrower type. | typeof / in / instanceof | if (typeof id === "string") id.toUpperCase(); |
Utility Types
| Concept | Syntax | Example |
|---|---|---|
| Partial<T> Perfect for update/patch functions. | all props optional | function update(u: Partial<User>) {} |
| Pick / Omit Build smaller shapes from bigger ones. | Pick<T, K> / Omit<T, K> | type Preview = Pick<User, "id" | "name">; |
| Record<K, V> A typed dictionary. | object with key/value types | const scores: Record<string, number> = {}; |
| ReturnType<T> Stay in sync with a function without retyping it. | extracts a function's return | type R = ReturnType<typeof getUser>; |