TypeScript
Updated: May 21, 2026Categories: Languages, Web, Backend, Frontend
Printed from:
Complete TypeScript Cheatsheet
Targets TypeScript 5.x (modern flags, decorators, satisfies, const type parameters).
Table of Contents
- Setup
tsconfig.json- Basic Types
- Functions
- Interfaces vs Type Aliases
- Generics
- Narrowing & Type Guards
- Utility Types
- Advanced Types
- Classes
- Modules
- Enums (and what to use instead)
satisfiesandas const- Conditional & Mapped Types
- Template Literal Types
- Decorators
- Declaration Files (
.d.ts) - Working with JS Libraries
- Common Patterns
- Quick Reference
Setup
Bash
12345678910111213# Install
pnpm add -D typescript @types/node
pnpm exec tsc --init # creates tsconfig.json
# Run TS directly
pnpm add -D tsx # or use bun / deno / node --import tsx
pnpm exec tsx script.ts
node --import tsx script.ts # Node 22+
# Typecheck only (don't emit JS)
pnpm exec tsc --noEmit
pnpm exec tsc -w # watch mode
tsconfig.json
jsonc
1234567891011121314151617181920212223242526272829303132{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext", // or "ESNext" for bundlers
"moduleResolution": "NodeNext", // or "Bundler"
"lib": ["ES2022", "DOM"],
"strict": true, // enable ALL strict flags
"noUncheckedIndexedAccess": true, // arr[i] is T | undefined
"exactOptionalPropertyTypes": true, // {a?: T} can't be {a: undefined}
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"isolatedModules": true, // each file is a module
"jsx": "preserve", // or "react-jsx"
"outDir": "dist",
"rootDir": "src",
"sourceMap": true,
"declaration": true,
"declarationMap": true,
"paths": {
"@/*": ["src/*"]
}
},
"include": ["src"],
"exclude": ["dist", "node_modules"]
}
Useful preset: @tsconfig/node22, @tsconfig/strictest, @tsconfig/recommended.
Basic Types
ts
123456789101112131415161718192021222324252627// Primitives
let n: number = 1;
let s: string = "x";
let b: boolean = true;
let big: bigint = 10n;
let sym: symbol = Symbol("k");
let u: undefined;
let nl: null;
// Arrays & tuples
let arr: number[] = [1, 2, 3];
let arr2: Array<number> = [1];
let tup: [string, number] = ["a", 1];
let tup2: readonly [string, number] = ["a", 1]; // immutable
let tup3: [string, ...number[]] = ["x", 1, 2]; // rest
// Objects
let user: { id: number; name: string; email?: string } = { id: 1, name: "Ada" };
// Special
let any1: any; // ⚠️ opt out of typing
let unknown1: unknown; // safe any — must narrow before use
let never1: never; // unreachable / impossible
let void1: void; // function returns nothing
let obj1: object; // any non-primitive
let fn1: Function; // ⚠️ avoid; use signatures
Functions
ts
123456789101112131415161718192021function add(a: number, b: number): number { return a + b; }
const sub = (a: number, b: number): number => a - b;
// Optional / default / rest
function greet(name: string, title = "Dr", ...tags: string[]) {}
// Overloads
function fmt(x: number): string;
function fmt(x: Date): string;
function fmt(x: number | Date): string {
return x instanceof Date ? x.toISOString() : String(x);
}
// Function types
type Handler = (event: string, payload?: unknown) => void;
type AsyncFn<T> = () => Promise<T>;
// `this` type
function dial(this: { phone: string }) { return this.phone; }
Interfaces vs Type Aliases
ts
1234567891011121314interface User {
id: number;
name: string;
greet(other: string): string;
}
interface Admin extends User { role: "admin"; } // extends
interface User { lastLogin?: Date; } // declaration merging
type Point = { x: number; y: number };
type Line = { start: Point; end: Point }; // composition
type PointOrLine = Point | Line; // unions (types only)
type Coords = Point & { z?: number }; // intersection
Rule of thumb:
interfacefor object shapes you might extend / merge.typefor unions, intersections, mapped/conditional types, primitives.
Generics
ts
12345678910111213141516171819202122function identity<T>(x: T): T { return x; }
identity<number>(1);
identity("x"); // inferred
// Constraints
function head<T extends readonly unknown[]>(arr: T): T[0] { return arr[0]; }
// Defaults
type Result<T = string, E = Error> = { ok: true; value: T } | { ok: false; error: E };
// Generic interfaces / classes
interface Box<T> { value: T }
class Stack<T> {
private items: T[] = [];
push(x: T) { this.items.push(x); }
pop(): T | undefined { return this.items.pop(); }
}
// Const type parameters (TS 5.0+) — preserve literal types
function tuple<const T extends readonly unknown[]>(...args: T): T { return args; }
const t = tuple("a", 1, true); // readonly ["a", 1, true]
Narrowing & Type Guards
ts
123456789101112131415161718192021222324252627function fn(x: string | number) {
if (typeof x === "string") x.toUpperCase();
else x.toFixed();
}
// in operator
function area(s: { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number }) {
if (s.kind === "circle") return Math.PI * s.r ** 2;
return s.w * s.h;
}
// instanceof
if (e instanceof Error) console.log(e.message);
// User-defined type guards
function isString(x: unknown): x is string {
return typeof x === "string";
}
// Assertion functions
function assertDefined<T>(x: T | undefined, msg = "missing"): asserts x is T {
if (x === undefined) throw new Error(msg);
}
// Exhaustiveness check via `never`
function exhaustive(x: never): never { throw new Error(`Unhandled: ${x}`); }
Utility Types
ts
123456789101112131415161718192021222324252627282930type U = { id: number; name: string; email?: string };
Partial<U> // all optional
Required<U> // all required
Readonly<U> // all readonly
Pick<U, "id" | "name"> // subset
Omit<U, "email"> // remove keys
Record<string, U> // { [k: string]: U }
Exclude<"a" | "b" | "c", "a"> // "b" | "c"
Extract<"a" | "b" | "c", "a" | "z"> // "a"
NonNullable<string | null | undefined> // string
// Functions
type F = (a: string, b: number) => boolean;
Parameters<F> // [string, number]
ReturnType<F> // boolean
Awaited<Promise<string>> // string
// Classes
ConstructorParameters<typeof Date>
InstanceType<typeof Date>
ThisParameterType<F>
OmitThisParameter<F>
// Strings (TS 4.1+)
Uppercase<"foo"> // "FOO"
Lowercase<"FOO"> // "foo"
Capitalize<"foo"> // "Foo"
Uncapitalize<"Foo"> // "foo"
Advanced Types
ts
1234567891011121314151617181920// Union & intersection
type StrOrNum = string | number;
type Both = { a: number } & { b: string };
// Discriminated union
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; size: number };
// keyof / typeof / indexed access
type Keys = keyof U; // "id" | "name" | "email"
type Email = U["email"]; // string | undefined
const settings = { lang: "en", theme: "dark" } as const;
type Lang = typeof settings.lang; // "en"
// `as const` makes everything readonly + literal
const TAGS = ["red", "green", "blue"] as const;
type Tag = typeof TAGS[number]; // "red" | "green" | "blue"
Classes
ts
12345678910111213141516171819202122232425class Animal {
protected name: string;
static kingdom = "Animalia";
constructor(name: string, public readonly id: number) {
this.name = name;
}
greet() { return `Hi, I'm ${this.name}`; }
}
class Dog extends Animal {
bark() { return "woof"; }
}
// Abstract
abstract class Shape { abstract area(): number; }
class Circle extends Shape { constructor(public r: number) { super(); } area() { return Math.PI * this.r ** 2; } }
// Access modifiers
class C { private p = 1; protected q = 2; public r = 3; readonly s = 4; }
// Parameter properties (shortcut)
class Point { constructor(public x: number, public y: number) {} }
Modules
ts
1234567891011121314151617// ESM (recommended)
export function add(a: number, b: number) { return a + b; }
export const PI = 3.14;
export default class App {}
import App, { add, PI } from "./module";
import * as M from "./module";
import type { Foo } from "./types"; // type-only import (erased at compile)
import { type Foo, bar } from "./mixed";
// Re-export
export { add } from "./module";
export * from "./module";
// CommonJS interop
import express = require("express"); // if esModuleInterop is off
Enums (and what to use instead)
ts
12345678910111213// Numeric enum
enum Direction { Up, Down, Left, Right }
// String enum (more debuggable)
enum Status { Active = "active", Inactive = "inactive" }
// Const enum (inlined at compile time, but tricky with isolatedModules / bundlers)
const enum Level { Low, Mid, High }
// ⭐ Preferred modern pattern: union of string literals + as-const object
const Status = { Active: "active", Inactive: "inactive" } as const;
type Status = typeof Status[keyof typeof Status]; // "active" | "inactive"
satisfies and as const
ts
12345678910111213141516// `satisfies` validates against a type WITHOUT widening
const colors = {
red: "#ff0000",
green: "#00ff00",
} satisfies Record<string, `#${string}`>;
colors.red; // type: "#ff0000" (literal preserved)
// vs. annotation, which widens:
const c2: Record<string, string> = { red: "#ff0000" };
c2.red; // type: string (literal lost)
// `as const` freezes everything to readonly + literal
const config = { mode: "prod", retries: 3 } as const;
// ^? readonly { mode: "prod"; retries: 3 }
Conditional & Mapped Types
ts
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950// Conditional
type IsString<T> = T extends string ? true : false;
type A = IsString<"x">; // true
type B = IsString<1>; // false
// `infer` to extract types
type ElementOf<T> = T extends (infer U)[] ? U : never;
type N = ElementOf<number[]>; // number
type ReturnTypeOf<F> = F extends (...args: any)O�[��\������]�\����\��X�][ۈݙ\�[�[ۜ�
^[���������B�\H�\��^O�H^[��[�H��H��]�\�\HH�\��^O��[���[X�\�������[���H�[X�\��B����X\Y�\H�[ۘ[^�O�H���[��^[وOΈ��HN\H��[��Y�O�H���[��^[وN���[��N\H]]X�O�H�\�XYۛH��[��^[وN���HN\H�\]Z\�Y��H���[��^[وKOΈ��HN\H�[�[YO�H���[��^[و\��] ��\][^�O��[�� �ϟXN�
HO���HN��KKB����[\]H]\�[\\�\HܙY][��H[� ���[��X\H��]HH����[��X����[��K����[��X\HY]�H��U������U��SUH�\H[��[�H �Y]�H����[��X�����X�[�Y�]X\Y�\H]�[�[�\���H��[��^[و ���[��\�ۉ��\][^�OϟXN�
����JHO���YN\HH]�[�[�\����X�Έ[�\�Q]�[�����\Έ���\�]�[�O����ې�X�Έ
��[�\�Q]�[�
HO���Y�ۑ���\Έ
�����\�]�[�
HO���YB���KKB����X�ܘ]ܜ��
K�
��\�
���Y�Hʊ�X�ܘ]ܜ�
Y��\�[����HH�\�^\�[Y[�[X�ܘ]ܜ��Y�K����[��[ۈ���Y\�\���^[��[�V�K�]\����\��]�
\Έ\����\��Έ\���HO��]\������\��Y]�X�ܘ]ܐ�^\ς�H�]\���[��[ۈ
\Έ\����\��Έ\���H�ۜ��K��� ���[�����[YJ_J\����H�N�]\��\��]�\J\�\���NNB���\���[����Y�Y
N��[X�\����[X�\�H��]\��H
���B�B���Y�X�HX�ܘ]ܜ��[[�\�H�܈[��[\���\����\SԓH�XH�^\�[Y[�[X�ܘ]ܜȎ��YX���KKB����X�\�][ۈ�[\�
���
B����\\���ؘ[��X�\�H�ؘ[[�\��X�H�[������TՑT��Sӗ�Έ��[���B��[Y\�X�H��R���[�\��X�H���\��[���UP�T�W�T����[���HB�B�^ܝ�N���[�[\����YK[X���X�\�H[�[H���YK][�\Y[X��^ܝ�[��[ۈ��Y�����[��N��[X�\�B����[X�Y[��[Y\X�\�H�ۜ���U��Έ���X[����[�\�]Y���H[�\���H�]�X�\�][ۈ���YX�܈X��\�Y\˂��KKB�����ܚ�[���]��X��\�Y\��\����[�\\�HYQ\\���\�\\�ۛ�B���Y���\\�^\���K�ܙX]H\\��X�����[�X�\�H]
�YHX�ݙJB����܈���Y^X�Y\��܈��ZYۛܙH]H[\ܝ[�H
\��\H]�
B���������[��YH����[\��ܚ���ʊ�\H�[\ܝ
���\\ȊK�\�\�H
��ۜ�HH�Y�K�[YN��YH�N��KKB������[[ۈ]\��������[�Y���Z[�[\\\H\�\�YH��[�� ���XYۛH��[���\�\�Y�N�ۜ�YH�X�Ȉ\�\�\�Y������\�[�Z]\��\H�\�[HH\���B���Έ�YN��[YN�B���Έ�[�N�\���HN������Z[\��][��H�]B��\��O�[X�Y^[����[��H�]�\���[X��^[����[�ϊΈ�H��]\��\�\�[�ۛ�ۈ\�O�[X�Yώ�B�B��������
�[�[YH�[Y][ۈ]ZY[��]X�\\�B�[\ܝ��H���H�����ۜ�\�\�H��ؚ�X�
�Y����[X�\�
K�[YN�����[��
HJN\H\�\�H��[��\�\[و\�\���ۜ�HH\�\��\��J�]�N�������Y�[��[Y�������\X�H[�H�][�ۛ�ۈ�܈[�]�[��[ۈ�Y�J�[�ۛ�ۊHY�
\[وOOH���[�ȊH�]\����\\��\�J
N�]\����B���������Y^X�Y\��ܘ��Y�\��Y^X�Y\��ܘݙ\��ZYۛܙX8�%]\��ܜ�Y�H[�\�Z[��\��YH\��^Y���KKB����]ZX���Y�\�[��B����\H���[YB��ۜ��HN����[YB�\H�H\[و����\HB����[�^X��\�\HH\�\�ț�[YH�N����^[٘�[��\H�H�^[و\�\�\HHH��[��N���[��N����[�\�X��[��[ۈ���
N���]\���B��[��[ۈ�^[����ϊ�
H�B��[��[ۈ�H��[�ϊ
H�B�����\����[�\[وOOH���[�Ȉ�[��[��[و���Ȉ[��\�
�YX�]JB�\��\��\�
\��\�[ۊB����][]H�X]�Y]�\�X[�\]Z\�Y�XYۛHX���Z]�X�ܙ�^�YH^�X��ۓ�[X�B�\�[Y]\���]\��\H]�Z]Y�ۜ��X�ܔ\�[Y]\��[��[��U\B�\\��\�H��\��\�H�\][^�H[��\][^�B����[�\��Y[�\�ۜ�H�N�HH\��ۜ��ۜ�HH�N�HH�]\ٚY\��N��[X�\�N�[��[ۈ���ۜ���
N���]\���B�[\ܝ\H����H���H�������[\ܝ��^ܝ^ܝ�ۜ�HN^ܝY�][�\���B�^ܝ
����H���H�^ܝ\H����H���H���H����
��\���\��ۈ���X����YX
��\ʊ����[��X��Y[�^YX��\�Ș[��^X��[ۘ[��\�U\\Ș��XX��܈�]\ٚY\�
��[���][ۜ�H�[�[�H�[�]\�[\\��\�\��Y��Y�\�[�\��X�X�܈ؚ�X��\X�܈[�[ۜ��][]Y\˂
Continue Learning
Discover more cheatsheets to boost your productivity