TypeScript Cheatsheet
Every essential TypeScript pattern: annotations, interfaces, generics, unions, utility types, and advanced patterns, with syntax and real use cases.70 commands · 7 sections
TypeScript adds a type system to JavaScript. This cheatsheet covers the patterns you write daily: primitive annotations, interfaces and type aliases, generics, unions and intersections, utility types, and the advanced patterns that make large codebases safe.
Every entry shows real syntax followed by the use case: when and why you reach for it.
Basic Types & Annotations12
const n: number = 42const s: string = "hi"const b: boolean = trueconst a: number[] = [1, 2]const t: [string, number] = ["a", 1]const x: unknown = JSON.parse(raw)const x: any = ...const f: () => void = () => {}let x: string | null = nullconst n: number = parseInt(s, 10)const x = value as stringconst x = value!Interfaces & Type Aliases10
interface User {
id: number
name: string
}interface User { id: number }
interface User { email: string }interface A extends B { }interface User {
name?: string
}interface User {
readonly id: number
}type ID = string | numbertype Callback = (err: Error | null, data?: unknown) => voidtype Status = "idle" | "loading" | "success" | "error"interface Indexed { [key: string]: number }interface User {
[key: string]: unknown
}Generics8
function identity<T>(x: T): T {
return x
}interface Box<T> {
value: T
}type Result<T> = { ok: true; value: T } | { ok: false; error: string }function f<T extends HasId>(x: T)function f<T, U>(a: T, b: U)async function fetchJson<T>(url: string): Promise<T>class Stack<T> { push(x: T) {} }function f<T = string>(x: T)Union & Intersection Types7
type A = string | numberif (typeof x === "string")"key" in objif (Array.isArray(x))interface Circle { kind: "circle"; radius: number }
interface Square { kind: "square"; size: number }type Admin = User & { role: "admin" }const exhaustive: never = xUtility Types13
Partial<User>Required<User>Pick<User, "id" | "name">Omit<User, "password">Readonly<User>Record<string, number>ReturnType<typeof fn>Parameters<typeof fn>Exclude<"a" | "b" | "c", "a">Extract<"a" | "b", "a" | "c">NonNullable<T>Awaited<Promise<T>>string | number extends `${infer U}` ? U : neverFunctions & Classes10
function f(a: number, b?: string): booleanconst f = (x: number): number => x * 2function f(...rest: string[]): voidfunction f(x: number): number | undefinedclass User {
constructor(private name: string) {}
}class User {
private secret = ""
protected role = "user"
public name = ""
}class User {
static create(): User { return new User() }
}class A implements B { }class Dog extends Animal {
constructor() { super() }
}abstract class Shape { abstract area(): number }Advanced Patterns10
satisfiesas consttype Keys = keyof typeof objtype V = T[K]type Mapped = { [K in keyof T]: boolean }function f<T extends object>(obj: T): T & { saved: true }declare module "*.css" { const css: string; export default css }declare global {
interface Window { gtag?: (a: string, b: unknown) => void }
}import type { User } from "./types"type Narrow<T> = T extends string ? "str" : "other"TypeScript Cheatsheet
Every essential TypeScript pattern: annotations, interfaces, generics, unions, utility types, and advanced patterns, with syntax and real use cases.
TypeScript adds a type system to JavaScript. This cheatsheet covers the patterns you write daily: primitive annotations, interfaces and type aliases, generics, unions and intersections, utility types, and the advanced patterns that make large codebases safe.
Every entry shows real syntax followed by the use case: when and why you reach for it.
Basic Types & Annotations
const n: number = 42: Annotate a number.const s: string = "hi": Annotate a string.const b: boolean = true: Annotate a boolean.const a: number[] = [1, 2]: Array type: also string[], boolean[].const t: [string, number] = ["a", 1]: Tuple: fixed length and types.const x: unknown = JSON.parse(raw): Unknown: safe for unvalidated data; narrow before use.const x: any = ...: Any: disables checks. Escape hatch, not a default.const f: () => void = () => {}: Function type annotation.let x: string | null = null: Nullable type: union with null.const n: number = parseInt(s, 10): Type for parsed values: parse returns number, not string.const x = value as string: Type assertion: override when YOU know more than TS.const x = value!: Non-null assertion: "trust me, it is defined".Interfaces & Type Aliases
interface User {
id: number
name: string
}: Define an object shape: the core TypeScript declaration.interface User { id: number }
interface User { email: string }: Declaration merging: extend the same interface across files.interface A extends B { }: Interface inheritance.interface User {
name?: string
}: Optional property: may be absent.interface User {
readonly id: number
}: Readonly property: cannot be reassigned.type ID = string | number: Type alias: unions, primitives, anything.type Callback = (err: Error | null, data?: unknown) => void: Alias for function signatures: reusable callback types.type Status = "idle" | "loading" | "success" | "error": Union of string literals: enumerate valid values.interface Indexed { [key: string]: number }: Index signature: dictionaries and maps.interface User {
[key: string]: unknown
}: Index signature for unknown props: flexible objects.Generics
function identity<T>(x: T): T {
return x
}: Generic function: type follows the caller.interface Box<T> {
value: T
}: Generic interface: containers and wrappers.type Result<T> = { ok: true; value: T } | { ok: false; error: string }: Generic discriminated union: the Result pattern.function f<T extends HasId>(x: T): Generic with constraint: T must have an id.function f<T, U>(a: T, b: U): Multiple type parameters.async function fetchJson<T>(url: string): Promise<T>: Generic async: type-safe API calls.class Stack<T> { push(x: T) {} }: Generic class.function f<T = string>(x: T): Default type parameter.Union & Intersection Types
type A = string | number: Union: value is one of these.if (typeof x === "string"): Narrow a union with typeof."key" in obj: Narrow with the in operator: property presence.if (Array.isArray(x)): Narrow arrays vs single values.interface Circle { kind: "circle"; radius: number }
interface Square { kind: "square"; size: number }: Discriminated union: each member has a literal tag.type Admin = User & { role: "admin" }: Intersection: combine types into one.const exhaustive: never = x: Never: exhaustiveness check; compiler errors on unhandled cases.Utility Types
Partial<User>: All properties optional: update payloads.Required<User>: All properties required.Pick<User, "id" | "name">: Select specific properties.Omit<User, "password">: Remove specific properties.Readonly<User>: All properties readonly: frozen configs.Record<string, number>: Object map type: keys to values.ReturnType<typeof fn>: A function's return type: derive without rewriting.Parameters<typeof fn>: A function's parameter tuple.Exclude<"a" | "b" | "c", "a">: Remove members from a union.Extract<"a" | "b", "a" | "c">: Keep only intersecting members.NonNullable<T>: Strip null and undefined.Awaited<Promise<T>>: Unwrap promise types: async helper types.string | number extends `${infer U}` ? U : never: Template literal types: derive from string patterns (advanced).Functions & Classes
function f(a: number, b?: string): boolean: Typed signature: optional param and return type.const f = (x: number): number => x * 2: Typed arrow function.function f(...rest: string[]): void: Typed rest parameters.function f(x: number): number | undefined: Union return: may fail gracefully.class User {
constructor(private name: string) {}
}: Parameter properties: shorthand for private fields.class User {
private secret = ""
protected role = "user"
public name = ""
}: Access modifiers: private, protected, public.class User {
static create(): User { return new User() }
}: Static members: factories and singletons.class A implements B { }: Implement an interface: contract enforcement.class Dog extends Animal {
constructor() { super() }
}: Class inheritance with super call.abstract class Shape { abstract area(): number }: Abstract class: blueprint with abstract methods.Advanced Patterns
satisfies: Check a value against a type WITHOUT widening it: keeps literal types.as const: Freeze literals: readonly tuple/object literal types.type Keys = keyof typeof obj: Keyof: keys of an object type as a union.type V = T[K]: Indexed access type: the type of a property.type Mapped = { [K in keyof T]: boolean }: Mapped types: transform every property.function f<T extends object>(obj: T): T & { saved: true }: Intersection return: augment what you return.declare module "*.css" { const css: string; export default css }: Module declaration: type ambient modules.declare global {
interface Window { gtag?: (a: string, b: unknown) => void }
}: Augment global types: extend Window, NodeJS.ProcessEnv.import type { User } from "./types": Type-only import: erased at compile time, no runtime cycle.type Narrow<T> = T extends string ? "str" : "other": Conditional types: choose a type based on another.Frequently asked questions
What is the difference between interface and type?
Interfaces can be merged and extended, and are preferred for object shapes and public APIs. Type aliases handle unions, intersections, tuples, and mapped types. Modern guidance: interface for objects, type for everything else.
How do generics work?
Generics parameterize types: function identity<T>(x: T): T captures the caller type at each call site. They build reusable components like Array<T> and Promise<T> while keeping full type safety.
What are union and intersection types?
A union (A | B) means a value can be A or B: narrow it with typeof, in, or discriminated union checks. An intersection (A & B) combines both types into one, used to merge config objects or mixins.
What are utility types used for?
Utility types transform existing types: Partial makes all properties optional, Pick/omit select fields, Record builds object maps, ReturnType extracts a function return type, and Exclude/Extract filter unions.