Cheatsheets / TypeScript

TypeScript Cheatsheet

Complete TypeScript reference. Hit Ctrl+P to print.

Primitive Types

let n: number = 42Number - integer or float
let s: string = "hello"String
let b: boolean = trueBoolean
let u: undefined = undefinedUndefined
let nu: null = nullNull
let sym: symbol = Symbol("key")Symbol
let big: bigint = 9007199254740991nBigInt
let x: anyany - opt out of type checking
let x: unknownunknown - like any but requires type check before use
function fail(): never { throw new Error() }never - function that never returns
function log(): void { console.log() }void - function returns nothing
let x = 42Type inference - TypeScript infers number

Arrays & Tuples

let arr: number[] = [1, 2, 3]Typed array
let arr: Array<string> = ["a", "b"]Generic array syntax
let pair: [string, number] = ["age", 30]Tuple - fixed length, typed positions
let tuple: [string, ...number[]] = ["n", 1, 2, 3]Rest element in tuple
const arr: readonly number[] = [1, 2]Read-only array
const arr: ReadonlyArray<number> = [1, 2]Generic read-only array

Interfaces & Type Aliases

interface User { id: number; name: string; }Interface definition
interface User { email?: string; }Optional property
interface User { readonly id: number; }Read-only property
interface User { [key: string]: unknown; }Index signature - dynamic properties
interface Admin extends User { role: string; }Interface extension
interface A extends B, C { }Extend multiple interfaces
type Point = { x: number; y: number; }Type alias - object shape
type ID = string | numberUnion type alias
type Named = { name: string } & { age: number }Intersection type
type Alias = stringSimple type alias

Functions

function add(a: number, b: number): number { return a + b; }Typed function
const add = (a: number, b: number): number => a + bArrow function with types
function greet(name?: string): stringOptional parameter
function greet(name: string = "World"): stringDefault parameter
function sum(...nums: number[]): numberRest parameter
type AddFn = (a: number, b: number) => numberFunction type alias
interface AddFn { (a: number, b: number): number }Function interface
function id<T>(x: T): T { return x; }Generic function
function first<T>(arr: T[]): T | undefinedGeneric with constraint
function len<T extends { length: number }>(x: T): numberGeneric with constraint
function parse(x: string): number; function parse(x: number): string;Function overloads

Classes

class User { name: string; constructor(name: string) { this.name = name; } }Basic class
class User { constructor(public name: string, private id: number) {} }Constructor shorthand - declares and assigns
class User { readonly id: number = Math.random(); }Readonly property
class User { #secret = "hidden"; }Private field (ES private - truly private)
class User { private secret = "hidden"; }TypeScript private - compile-time only
class User { protected role = "user"; }Protected - accessible in subclasses
class Admin extends User { }Class inheritance
super(args)Call parent constructor
class User implements IUser { }Implement interface
abstract class Shape { abstract area(): number; }Abstract class and method
class Box<T> { constructor(public value: T) {} }Generic class
get name(): string { return this._name; }Getter
set name(v: string) { this._name = v; }Setter
static count = 0Static class property

Union, Intersection & Narrowing

type ID = string | numberUnion type
type Named = { name: string } & { age: number }Intersection type - merge all properties
if (typeof x === "string") { }typeof narrowing
if (x instanceof Date) { }instanceof narrowing
if ("name" in obj) { }in narrowing - check property existence
if (x === null) { }Null check narrowing
function isUser(x: any): x is User { return "name" in x; }Type predicate (user-defined type guard)
function assertUser(x: any): asserts x is User { }Assertion function
x!Non-null assertion - tells TS x is not null/undefined
x as stringType assertion (cast)
x as unknown as TDouble assertion - bypass incompatible cast

Generics

function wrap<T>(val: T): { value: T }Generic function
interface Box<T> { value: T }Generic interface
type Pair<A, B> = { first: A; second: B }Generic type alias
<T extends string | number>Constrain generic to specific types
<T extends object>Constrain to object types
<T, U extends T>U must extend T
function getProp<T, K extends keyof T>(obj: T, key: K): T[K]keyof constraint
<T = string>Generic default type

Utility Types

Partial<User>All properties optional
Required<User>All properties required
Readonly<User>All properties read-only
Pick<User, "id" | "name">Keep only specified properties
Omit<User, "password">Remove specified properties
Record<string, number>Object with specific key and value types
Exclude<"a" | "b" | "c", "a">Remove types from union - result: "b" | "c"
Extract<"a" | "b" | number, string>Keep types in union - result: "a" | "b"
NonNullable<string | null | undefined>Remove null and undefined - result: string
ReturnType<typeof fn>Infer return type of a function
Parameters<typeof fn>Infer parameter types as tuple
InstanceType<typeof MyClass>Infer instance type of a class
Awaited<Promise<string>>Unwrap promise type - result: string

Mapped & Conditional Types

type Opt<T> = { [K in keyof T]?: T[K] }Mapped type - make all optional
type Ro<T> = { readonly [K in keyof T]: T[K] }Mapped type - make all read-only
type Str<T> = { [K in keyof T]: string }Remap all values to string
type GetStr<T> = T extends string ? T : neverConditional type
T extends U ? X : YConditional type syntax
type Flat<T> = T extends Array<infer U> ? U : Tinfer - extract type within conditional
type Keys<T> = keyof Tkeyof - union of property keys
type Val<T, K extends keyof T> = T[K]Indexed access type
type E = 'a' | 'b'; type Obj = { [K in E]: K }Template mapped type over union
`${string}Id`Template literal type
Uppercase<S> / Lowercase<S> / Capitalize<S>Intrinsic string manipulation types

Enums & Literals

enum Direction { Up, Down, Left, Right }Numeric enum - values 0, 1, 2, 3
enum Direction { Up = "UP", Down = "DOWN" }String enum
const enum Size { S = 1, M, L }Const enum - inlined at compile time
type Dir = "up" | "down" | "left"String literal union - preferred over enum
type Code = 200 | 404 | 500Numeric literal union
const obj = { a: 1, b: 2 } as constas const - narrow to literal types, readonly
type Keys = keyof typeof objExtract keys of a const object as union
type Vals = typeof obj[keyof typeof obj]Extract values of a const object as union
const directions = ["north","south","east","west"] as constas const on array - creates readonly tuple of literals
type Direction = typeof directions[number]Union type from const array: 'north'|'south'|...

Modules & Declarations

export type { User }Type-only export (erased at runtime)
import type { User } from "./types"Type-only import
declare const __DEV__: booleanAmbient declaration - no implementation
declare module "*.svg" { const src: string; export default src; }Module augmentation for non-TS files
declare global { interface Window { myVar: string; } }Augment global types
/// <reference types="node" />Triple-slash directive - include type definitions
"strict": true in tsconfig.jsonEnable all strict checks - recommended
"noUncheckedIndexedAccess": trueIndex signatures return T | undefined

Advanced Type Patterns

type Vals = (typeof arr)[number]Get array element type
type StringKeys<T> = { [K in keyof T]: T[K] extends string ? K : never }[keyof T]Filter keys by value type
type Flatten<T> = T extends Array<infer U> ? U : TFlatten array type one level
type DeepReadonly<T> = { readonly [K in keyof T]: DeepReadonly<T[K]> }Recursive mapped type pattern
type RequiredFields<T, K extends keyof T> = T & Required<Pick<T, K>>Make specific fields required

Template Literal Types

type EventName = `on${string}`Template literal type
type PropEvent<T extends string> = `${T}Changed`Parameterised template literal
type Getter<T extends string> = `get${Capitalize<T>}`With intrinsic string utility
Uppercase<T>Intrinsic: uppercase string type
Lowercase<T>Intrinsic: lowercase string type
Capitalize<T>Intrinsic: capitalize first char
Uncapitalize<T>Intrinsic: lowercase first char
type Endpoint = `${'GET'|'POST'} ${'/users'|'/posts'}`Combine unions in template literal (generates all combos)

Discriminated Unions

type Shape = { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number }Discriminated union with kind tag
switch (shape.kind) { case "circle": ... }Discriminant narrows the union
if (shape.kind === "circle") shape.rNarrows in if block
type Result<T> = { ok: true; value: T } | { ok: false; error: string }Discriminated Result type
function assertNever(x: never): never { throw new Error() }Exhaustiveness check

satisfies Operator

const palette = { red: [255,0,0] } satisfies Record<string, [number,number,number]>Validate type without widening (TypeScript 4.9+)
palette.redInferred as [number,number,number], not generic array
const config = { port: 3000 } satisfies { port: number; host?: string }Keeps literal types while checking shape