TS

TypeScript Cheatsheet

Core TypeScript syntax - type annotations, interfaces, generics, and the utility types used constantly in real codebases.

Basic types

let x: number

Type annotation

let x: string | null

Union type

let x: "a" | "b"

String literal union

let x: number[]

Array of numbers

let x: [string, number]

Tuple type

let x: unknown

Type-safe alternative to any

Interfaces & types

interface User { name: string }

Define an object shape

type User = { name: string }

Type alias (equivalent for objects)

interface Admin extends User {}

Extend an interface

name?: string

Optional property

readonly name: string

Read-only property

Generics

function id<T>(x: T): T

Generic function

interface Box<T> { value: T }

Generic interface

Array<string>

Generic array type

<T extends object>

Constrain a generic type

Utility types

Partial<T>

All properties optional

Required<T>

All properties required

Pick<T, "a" | "b">

Select specific properties

Omit<T, "a">

Exclude specific properties

Record<string, number>

Object type with key/value types