Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 96 ยท Practice and Review

TypeScript Cheat Sheet

A dense TypeScript 7 reference: types, unions, narrowing, functions, classes, generics, utility, mapped and conditional types, tsconfig and error codes.

This page packs the whole TypeScript course into one dense reference: the syntax you type every day, the type operators you look up every week, and the compiler options and error codes you meet every time you start a new project. Every snippet is short enough to scan in a few seconds. Keep it open next to the TypeScript programs and the practice exercises, or read it the evening before an interview.

Everything here is modern TypeScript 7 in strict mode. Features added in the 5.x releases are labeled with the version that introduced them, so you know what an older project can use. Each section links to the lesson that explains the topic properly, and the items that trip people up most come with live editors. Our editor type-checks first and then runs the program, so a type error means you see only the error list, never the output.

Running TypeScript

Terminal
npm install --save-dev typescript   # the compiler, per project
npx tsc --init                      # create tsconfig.json
npx tsc                             # type-check and emit JavaScript (uses tsconfig.json)
npx tsc --noEmit                    # type-check only (common with bundlers)
npx tsc --watch                     # re-check on every save
node main.ts                        # Node 22.18+/24: strips types and runs (no type check!)
  • Types are erased: the JavaScript that runs has no annotations, interfaces or type aliases left. Nothing about types can be checked at runtime unless you write the check yourself.
  • tsc is the only tool that type-checks. Node's type stripping, esbuild, Vite and Bun just delete the types, so run tsc --noEmit in CI.
  • TypeScript 7 is the native compiler written in Go: the same language as 5.x/6.0, roughly ten times faster. Options deprecated in 6.0 (target: es5, moduleResolution: node10, outFile, baseUrl) are gone.

Lessons: Getting Started, How TypeScript Works, TypeScript with Node.js.

Basic types

Annotations and inference

TypeScript
let title: string = 'Guide';      // annotation
let count = 3;                    // inferred: number
const mode = 'dark';              // inferred: the literal type 'dark'
let level = 'dark';               // inferred: string (let widens)

function area(width: number, height: number): number {
  return width * height;          // annotate parameters; the return type is optional
}

Annotate function parameters, exported functions and public APIs. Let inference handle local variables. See Your First Types and Type Inference.

Primitives and special types

Type Values Notes
string 'a', "b", `c${x}`
number 42, 3.14, NaN, Infinity, 0xff, 1_000 one type for ints and floats
bigint 10n, BigInt(10) can't mix with number in arithmetic
boolean true, false
symbol Symbol('id') unique symbol for a const
null, undefined null, undefined separate types under strictNullChecks
unknown anything safe top type: narrow before use
any anything turns checking off; avoid
never nothing impossible values, exhaustiveness
void undefined "the return value isn't used"
object any non-primitive rarely what you want

typeof at runtime returns 'string', 'number', 'bigint', 'boolean', 'symbol', 'undefined', 'function' or 'object' (also for null and arrays). Lessons: Primitive Types, any, unknown, never and void.

Arrays and tuples

TypeScript
const ids: number[] = [1, 2, 3];
const names: Array<string> = ['Ada', 'Lin'];
const frozen: readonly number[] = [1, 2];          // no push, no index assignment
const mixed: (string | number)[] = ['a', 1];       // array of a union

type Point = [x: number, y: number];               // named tuple elements
type Entry = [key: string, value?: number];        // optional element
type Row = [string, ...number[]];                  // rest element
const origin: readonly [0, 0] = [0, 0];
const pair = ['id', 7] as const;                   // readonly ['id', 7]

See Arrays and Tuples.

Object types

TypeScript
type User = {
  readonly id: number;        // can't be reassigned
  name: string;
  email?: string;             // optional: string | undefined when read
};

type Scores = { [player: string]: number };        // index signature
type Attrs = { [key: `data-${string}`]: string };  // template-literal keys
type ByRole = Record<'admin' | 'user', string[]>;  // exactly these keys
  • Excess property check: an object literal assigned to a typed target may not have unknown properties (TS2353). A variable holding the same object passes, because types are structural.
  • With noUncheckedIndexedAccess, scores['zoe'] has type number | undefined.

Lessons: Object Types, Index Signatures and Record, Object Types in Depth.

Interfaces vs type aliases

TypeScript
interface Animal {
  name: string;
  speak(): string;              // method syntax
}
interface Dog extends Animal {  // extend one or more interfaces
  breed: string;
}
interface Animal { age?: number }   // declaration merging: adds a member

type Id = string | number;          // unions need `type`
type Handler = (event: string) => void;
type Pet = Animal & { owner: string };  // intersection

Use interface for object shapes others may extend; use type for unions, tuples, functions and computed types. See Type Aliases and Interfaces.

Unions, literals and as const

TypeScript
type Status = 'idle' | 'loading' | 'done';    // a literal union: a lightweight enum
type Port = 80 | 443 | 8080;
let input: string | number = 5;

const config = { env: 'prod', retries: 3 } as const;
// { readonly env: 'prod'; readonly retries: 3 }

const ROLES = ['admin', 'editor', 'viewer'] as const;
type Role = (typeof ROLES)[number];           // 'admin' | 'editor' | 'viewer'

See Union Types and Literal Types and as const.

Enums

TypeScript
enum Direction { Up, Down }             // numeric: Up = 0, Down = 1
Direction[0];                           // 'Up' (reverse mapping, numeric enums only)
enum Level { Low = 'low', High = 'high' }  // string enum: no reverse mapping
const enum Flag { A = 1, B = 2 }        // inlined at compile time

Enums exist at runtime and are not erasable syntax, so --erasableSyntaxOnly (and Node's type stripping) rejects them. Many teams use a literal union or an as const object instead. See Enums.

Assertions

TypeScript
const el = value as string;             // trust me: no runtime check
const n = maybe!;                       // non-null assertion: removes null | undefined
const x = input as unknown as Date;     // double assertion: a red flag
const cfg = { port: 80 } satisfies { port: number };  // check without changing the type

See Type Assertions and the Non-Null Operator and The satisfies Operator.

Functions

TypeScript
function greet(name: string, greeting = 'Hello', suffix?: string): string {
  return `${greeting}, ${name}${suffix ?? ''}`;
}
function sum(...values: number[]): number { return values.reduce((a, b) => a + b, 0); }
const double = (n: number): number => n * 2;

type Comparator<T> = (a: T, b: T) => number;              // function type expression
type Formatter = { (value: number): string; locale: string };  // call signature + property
type Ctor<T> = new (...args: any[]) => T;                 // construct signature (any[] is the usual idiom here)

function onClick(this: { id: string }, label: string) { /* typed this */ }
function fail(message: string): never { throw new Error(message); }
  • A callback type that returns void accepts functions that return something: [1, 2].forEach((n) => list.push(n)) is fine.
  • A function with fewer parameters is assignable to a type with more.
  • Destructured parameters: function draw({ x, y }: Point2D) {}.

Overloads

TypeScript
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
  return Array.isArray(input) ? input.map(Number) : Number(input);
}

Callers see only the overload signatures, most specific first; the implementation signature is hidden. Prefer a union parameter when the return type doesn't depend on the input. Lessons: Typing Functions, Function Types and Callbacks, Function Overloads.

Narrowing

TypeScript
function show(value: string | number | null | Date | string[]) {
  if (value === null) return;                         // equality
  if (typeof value === 'string') value.toUpperCase(); // typeof
  else if (value instanceof Date) value.getFullYear();// instanceof
  else if (Array.isArray(value)) value.join(', ');    // Array.isArray
  else value.toFixed(2);                              // only number is left
}

if ('swim' in animal) animal.swim();                 // in operator
if (user.email) sendTo(user.email);                  // truthiness (careful with 0 and '')

function isString(x: unknown): x is string {          // type predicate
  return typeof x === 'string';
}
function assert(condition: unknown, message: string): asserts condition {
  if (!condition) throw new Error(message);          // assertion function
}
const present = [1, null, 3].filter((n) => n !== null);  // number[] (inferred predicate, 5.5)

Discriminated unions and exhaustiveness

The most useful pattern in TypeScript: every member has a common literal property, a switch on it narrows, and a never check makes the compiler tell you when a new case is missing.

TypeScript Discriminated union with an exhaustive switch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Add | { kind: 'square'; side: number } to Shape and run again: the program stops with error TS2322: Type '{ kind: "square"; side: number; }' is not assignable to type 'never'., pointing at the unreachable line. Lessons: Narrowing, Discriminated Unions, Custom Type Guards, this, Parameter Destructuring and Type Predicates.

Classes

TypeScript
abstract class Account {
  static count = 0;                         // static member
  #pin: string;                             // JavaScript private (real at runtime)
  protected balance = 0;                    // visible in subclasses (compile time only)
  accessor nickname = '';                   // auto-accessor (get/set pair)

  constructor(public readonly owner: string, pin: string) {  // parameter property
    this.#pin = pin;
    Account.count++;
  }
  get summary(): string { return `${this.owner}: ${this.balance}`; }
  abstract fee(): number;                   // subclasses must implement it
}

class Savings extends Account implements Comparable<Savings> {
  override fee(): number { return 0; }      // `override` required with noImplicitOverride
  compareTo(other: Savings): number { return this.balance - other.balance; }
}
interface Comparable<T> { compareTo(other: T): number }

let ready!: string;                         // definite assignment: "I'll set it before use"
type SavingsClass = typeof Savings;         // the constructor's type
type SavingsInstance = InstanceType<typeof Savings>;
  • private and protected are checked only by the compiler; #private is enforced by JavaScript.
  • strictPropertyInitialization: every field needs an initializer or a constructor assignment.

Lessons: Classes, Access Modifiers and Private Fields, Inheritance and Abstract Classes, Classes, Interfaces and Structural Typing.

Structural typing

TypeScript compares shapes, not names. A value fits a type when it has at least the required members with compatible types. Object literals are the exception: they get an extra check for unknown properties.

TypeScript Structural typing and excess property checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The // @ts-expect-error comment tells the compiler that the next line should fail, so the program still runs (it would be an error if the line compiled). Remove the comment to see error TS2353: Object literal may only specify known properties, and 'z' does not exist in type 'Point'. Lessons: Type Compatibility and Variance, Readonly and Immutability.

Generics

TypeScript
function first<T>(items: readonly T[]): T | undefined { return items[0]; }
first([1, 2]);                                       // T inferred as number

function longest<T extends { length: number }>(a: T, b: T): T {   // constraint
  return a.length >= b.length ? a : b;
}
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }

interface Box<T = string> { value: T }               // default type argument
class Stack<T> {
  #items: T[] = [];
  push(item: T): void { this.#items.push(item); }
  pop(): T | undefined { return this.#items.pop(); }
}

function asTuple<const T extends readonly unknown[]>(...xs: T): T { return xs; }  // 5.0
asTuple('a', 1);                                     // readonly ['a', 1]

function pickColor<C extends string>(options: C[], fallback: NoInfer<C>): C {     // 5.4
  return options[0] ?? fallback;
}

Lessons: Generics, Generic Constraints and Defaults, Generic Interfaces, Classes and Types.

Type operators

TypeScript
type User = { id: number; name: string; tags: string[] };
const defaults = { theme: 'light', size: 12 };

type UserKey = keyof User;               // 'id' | 'name' | 'tags'
type Defaults = typeof defaults;         // { theme: string; size: number }
type NameType = User['name'];            // string
type Tag = User['tags'][number];         // string (element type)
type IdOrName = User['id' | 'name'];     // number | string

See keyof, typeof and Indexed Access Types.

Built-in utility types

Utility Result
Partial<T> / Required<T> every property optional / required
Readonly<T> every property readonly (shallow)
Pick<T, 'a' | 'b'> / Omit<T, 'a'> keep / drop properties
Record<K, V> object with keys K and values V
Exclude<U, X> / Extract<U, X> remove / keep union members assignable to X
NonNullable<T> removes null and undefined
ReturnType<F> / Parameters<F> a function's return type / parameter tuple
ConstructorParameters<C> / InstanceType<C> the same for classes
Awaited<T> the value inside (nested) promises
NoInfer<T> (5.4) blocks inference from this position
Uppercase, Lowercase, Capitalize, Uncapitalize string literal transforms

See Built-in Utility Types.

Mapped, conditional and template literal types

TypeScript
type Optional<T> = { [K in keyof T]?: T[K] };                 // mapped
type Mutable<T> = { -readonly [K in keyof T]: T[K] };         // remove a modifier
type Getters<T> = {                                           // key remapping
  [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K];
};
type OnlyStrings<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K] };

type IsArray<T> = T extends readonly unknown[] ? true : false; // conditional
type ElementOf<T> = T extends readonly (infer E)[] ? E : never; // infer
type ToArray<T> = T extends unknown ? T[] : never;            // distributes over unions
type ToArrayNoDist<T> = [T] extends [unknown] ? T[] : never;  // doesn't distribute

type EventName<T extends string> = `on${Capitalize<T>}`;      // template literal
type Css = `${number}px` | `${number}%`;

Proving types with Expect and Equal

Type-level code has no output, so tests for types are compile-time checks: if a check fails, the program doesn't compile. This pair of helpers is used all over the course.

TypeScript Testing types with Expect and Equal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Change any expected type, for example 'getId' | 'getName', and the run stops with error TS2344: Type 'false' does not satisfy the constraint 'true'. Lessons: Mapped Types, Conditional Types, Template Literal Types, Advanced Type-Level Programming.

Modules and declarations

TypeScript
import { readFileSync } from 'node:fs';
import { save, type User } from './users.js';   // .js even for a .ts file under nodenext
import type { Config } from './config.js';      // erased completely
export type { User };
export default function main() {}

declare const VERSION: string;                  // exists at runtime, defined elsewhere
declare module 'legacy-lib' {                   // types for an untyped package
  export function slugify(text: string): string;
}
declare global {
  interface Array<T> { last(): T | undefined }  // global augmentation (in a module)
}
  • verbatimModuleSyntax: imports used only as types must say type, so tools know what to erase.
  • .d.ts files contain only declarations; @types/<package> comes from DefinitelyTyped.
  • // @ts-expect-error fails if the next line has no error; // @ts-ignore never fails. Prefer the first.

Lessons: Modules, Declaration Files, Namespaces, Migrating JavaScript to TypeScript.

Async, errors and iteration

TypeScript
async function load(id: number): Promise<User> { /* ... */ }
const [user, posts] = await Promise.all([load(1), loadPosts(1)]);   // a typed tuple
const results = await Promise.allSettled([load(1), load(2)]);       // PromiseSettledResult<User>[]
type Value = Awaited<ReturnType<typeof load>>;                      // User

try {
  risky();
} catch (error) {                              // error: unknown (useUnknownInCatchVariables)
  const message = error instanceof Error ? error.message : String(error);
}
class NotFoundError extends Error {
  override name = 'NotFoundError';
  constructor(readonly id: number) { super(`No item ${id}`); }
}
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };

function* count(to: number): Generator<number, string, void> {
  for (let i = 1; i <= to; i++) yield i;
  return 'done';
}
async function* lines(): AsyncGenerator<string> { yield 'a'; }

Lessons: Promises and async/await, Error Handling, Iterators and Generators.

Modern features

TypeScript
// satisfies (4.9): validate a value, keep its precise inferred type
const routes = { home: '/', about: '/about' } satisfies Record<string, string>;
routes.about;                                   // string, and routes.contact is an error

// using (5.2): dispose automatically at the end of the block
{
  using file = openFile('log.txt');             // file[Symbol.dispose]() runs on exit
  await using db = await connect();             // db[Symbol.asyncDispose]()
}

// standard decorators (5.0)
function logged<T, A extends unknown[], R>(
  method: (this: T, ...args: A) => R,
  context: ClassMethodDecoratorContext<T, (this: T, ...args: A) => R>,
) {
  return function (this: T, ...args: A): R {
    console.log(`calling ${String(context.name)}`);
    return method.call(this, ...args);
  };
}

satisfies checks against the type but keeps the inferred one: routes.about is string (properties of a mutable object widen), but the compiler knows the object has exactly home and about. Add as const before satisfies to keep the literal '/about'.

TypeScript satisfies vs a type annotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Lessons: The satisfies Operator, using Declarations, Decorators, What's New in TypeScript.

tsconfig.json essentials

JSON
{
  "compilerOptions": {
    "target": "es2024",
    "module": "nodenext",
    "lib": ["es2024"],
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "skipLibCheck": true,
    "declaration": true,
    "sourceMap": true,
    "outDir": "dist"
  },
  "include": ["src"]
}
Option What it does
strict turns on the whole strict family (strictNullChecks, noImplicitAny, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, useUnknownInCatchVariables, alwaysStrict, noImplicitThis, ...)
target which JavaScript version to emit (newer syntax is downleveled)
module / moduleResolution module format and how imports are found: nodenext for Node, bundler for Vite/esbuild apps
lib which built-in declarations exist (dom for browsers)
noUncheckedIndexedAccess arr[i] and record[key] include undefined
exactOptionalPropertyTypes x?: string no longer accepts an explicit undefined
verbatimModuleSyntax type-only imports must use import type
erasableSyntaxOnly (5.8) bans enum, namespace with code, parameter properties: syntax that isn't just erasable
noEmit check only; a bundler produces the JavaScript
skipLibCheck don't type-check .d.ts files in dependencies (faster)
declaration emit .d.ts files (libraries)

Our editor runs --strict --target es2024 --lib esnext --module nodenext --types node. Lessons: The tsconfig.json File, Strict Mode Explained.

Common error codes

Code Message (shortened) Usual fix
TS2322 Type 'X' is not assignable to type 'Y'. fix the value or widen the type
TS2345 Argument of type 'X' is not assignable to parameter of type 'Y'. pass the right type, narrow first
TS2339 Property 'p' does not exist on type 'T'. narrow the union, fix the name, extend the type
TS2353 Object literal may only specify known properties ... remove the extra key or add it to the type
TS2741 Property 'p' is missing in type ... but required in type ... add the property or make it optional
TS2554 Expected 2 arguments, but got 1. pass all required arguments
TS7006 Parameter 'x' implicitly has an 'any' type. annotate the parameter
TS18047 / TS18048 'x' is possibly 'null' / 'undefined'. check first, ?., ??
TS2531 / TS2532 Object is possibly 'null' / 'undefined'. same as above
TS18046 'x' is of type 'unknown'. narrow with typeof, instanceof or a guard
TS2367 This comparison appears to be unintentional ... no overlap. the values can never be equal: check the logic
TS2564 Property 'p' has no initializer and is not definitely assigned ... initialize it or assign in the constructor
TS2366 Function lacks ending return statement ... return on every path
TS2304 Cannot find name 'x'. import it, declare it, or add a lib
TS2307 Cannot find module 'm' ... install the package or its @types
TS7053 Element implicitly has an 'any' type because expression ... can't be used to index ... type the key as keyof T or add an index signature
TS2344 Type 'X' does not satisfy the constraint 'Y'. the type argument breaks a generic constraint

The format is always file(line,column): error TScode: message. See Best Practices and Common Mistakes for each one with an example.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of level after let level = 'dark';?

    let variables are widened to the general type, because they can be reassigned. const level = 'dark' would keep the literal type 'dark'.
  2. 2. What does type T = (typeof ROLES)[number] give when const ROLES = ['admin', 'viewer'] as const;?

    as const makes the array a readonly tuple of literals; indexing it with number gives the union of its element types.
  3. 3. Which statement about satisfies is correct?

    satisfies reports an error when the value doesn't match, but the variable keeps its precise inferred type, unlike an annotation (which replaces it) or as (which skips the check).
  4. 4. What is ToArray<string | number> with type ToArray<T> = T extends unknown ? T[] : never;?

    A conditional type on a naked type parameter distributes over unions, so it becomes ToArray<string> | ToArray<number>. Wrap both sides in brackets, [T] extends [unknown], to get (string | number)[].
  5. 5. Why does a discriminated union switch use const unreachable: never = shape in the default branch?

    When every case is handled, shape is narrowed to never and the assignment compiles. A forgotten member leaves a real type there, and assigning it to never fails with TS2322.

Summary

  • Types are erased at runtime and only tsc type-checks; Node's type stripping and bundlers only remove types.
  • Annotate parameters and public APIs, let inference do the rest, and remember that let widens while const keeps literals.
  • Model data with object types and interfaces, choices with literal unions, and state with discriminated unions plus a never exhaustiveness check.
  • Narrow with typeof, instanceof, in, equality, truthiness, type predicates and assertion functions; prefer unknown to any.
  • Generics with constraints, keyof, indexed access, utility types, mapped, conditional and template literal types let you derive types instead of repeating them; test them with Expect<Equal<...>>.
  • Use strict, noUncheckedIndexedAccess, verbatimModuleSyntax and friends, and learn to read file(line,column): error TScode messages.

Next: TypeScript Programs: 40 Classic Examples, complete programs that put these features to work.