Language :: TypeScript

TypeScript Handbook

TypeScript is a statically typed superset of JavaScript developed by Microsoft and first released in 2012. It compiles down to plain JavaScript and runs everywhere JS runs — browsers, Node.js, Deno, Bun, and edge runtimes. The type system is structural (duck-typed), not nominal, which makes it flexible enough to model complex JS patterns. TypeScript has become the de-facto standard for large-scale JavaScript projects: Angular, Next.js, Nuxt, Svelte, and Vue are all written in TypeScript.

Pick TypeScript when

  • Any JavaScript project that will grow — TypeScript catches entire classes of runtime bugs (undefined property access, wrong argument types) at compile time, for free. The migration cost from JS is low; the payoff in large codebases is enormous.
  • Team collaboration — types serve as living documentation. A new developer can understand an API contract by reading its types without running the code. IDEs give instant autocomplete and refactoring support.
  • Building a library or SDK — publishing .d.ts declaration files lets consumers of your library get full type checking without reading source. The ecosystem expects types now.
  • Complex domain modelling — discriminated unions, mapped types, conditional types, and template literal types let you encode business rules in the type system and have the compiler enforce them.
  • React, Vue, or Angular frontends — all three frameworks have first-class TypeScript support. Props types, store types, and route types eliminate entire categories of UI bugs.

Think twice before choosing TypeScript when

  • One-off scripts — if you're writing a 20-line script that runs once, the tsconfig setup and compilation step is overhead. Plain JS or Python is faster to reach for.
  • You need fully sound types — TypeScript's type system has intentional unsoundness (type assertions, any, structural subtyping of functions). For provably correct programs, use a language with a sound type system like Haskell, Elm, or Rust.
  • Build pipeline complexity is a concern — TypeScript requires a compilation step. In very simple setups (plain HTML + a CDN script tag), JS is easier.

TypeScript vs. its closest alternatives

  • TypeScript vs JavaScript — TypeScript is a strict upgrade for any project beyond a trivial script. The cost is near zero (especially with allowJs for gradual migration); the safety gains are large.
  • TypeScript vs Flow — Facebook's Flow is a similar typed JS project but has largely lost the ecosystem battle. TypeScript has better tooling, broader adoption, and more active development.
  • TypeScript vs Dart — Dart (Flutter) compiles to native mobile/desktop apps and has a sound type system. TypeScript is better for web; Dart is better for cross-platform native apps.
  • TypeScript vs Go/Rust for backend — TypeScript on Node is excellent for I/O-bound services and where JS ecosystem libraries are needed. Go and Rust win on raw throughput, binary size, and memory footprint for CPU-bound or high-concurrency services.

Your First Program

Install Node.js and the TypeScript compiler so that tsc is available on your PATH. Save this program as hello.ts.

The first string annotation constrains the argument and the second constrains the return value. The compiler checks both before Node runs the emitted JavaScript.

typescript
function greet(name: string): string {
    return "Hello, " + name + "!";
}

console.log(greet("Ada"));

Run these commands from the directory containing the source file. The output is Hello, Ada!

bash
tsc --strict hello.ts
node hello.js

Resources

Topics

Primitives & Literals

Primitive and literal types describe sets of possible values. Literal types preserve exact choices for discriminants and constrained arguments.

A literal type describes one exact value. A mutable variable initialized with a string usually widens to string, while a const binding can retain the literal. An object property can still widen because the object is mutable.

Choose a primitive or narrow unknown

typescript
// Primitive types
let name: string = 'Alice';
let age: number = 30;
let active: boolean = true;
let nothing: null = null;
let undef: undefined = undefined;
let id: symbol = Symbol('id');
let big: bigint = 100n;

// any (opt-out of type checking)
let loose: any = 'hello';
loose = 42;   // OK

// unknown (safer any — must narrow before use)
let input: unknown = getData();
if (typeof input === 'string') {
  input.toUpperCase();   // safe inside guard
}

// never (unreachable / always throws)
function fail(msg: string): never {
  throw new Error(msg);
}

Unknown requires a check before use.

Constrain values and collections

typescript
// Literal types
let direction: 'left' | 'right' | 'up' | 'down' = 'left';
let status: 200 | 400 | 404 | 500 = 200;
const PI = 3.14;   // type is 3.14, not number

// Arrays
let nums: number[] = [1, 2, 3];
let strs: Array<string> = ['a', 'b'];

// Tuple
let pair: [string, number] = ['Alice', 30];

// Readonly
const readOnly: readonly number[] = [1, 2, 3];

Literal types restrict values, while tuples type each position.

Unions & Intersections

Unions permit alternatives while intersections require all constituent constraints. Narrow a union before accessing members absent from some alternatives.

A union allows any of its alternatives. Until a check narrows the value, use operations valid for every alternative. An intersection requires the value to satisfy both sides.

Combine alternatives and requirements

typescript
// Union
type StringOrNumber = string | number;

function format(val: string | number): string {
  return String(val);
}

// Intersection
type Named = { name: string };
type Aged  = { age: number };
type Person = Named & Aged;

const p: Person = { name: 'Alice', age: 30 };

A union accepts either shape and an intersection requires both.

Select a variant by its tag

typescript
// Discriminated union (tagged union)
type Shape =
  | { kind: 'circle';    radius: number }
  | { kind: 'rectangle'; width: number; height: number };

function area(s: Shape): number {
  switch (s.kind) {
    case 'circle':    return Math.PI * s.radius ** 2;
    case 'rectangle': return s.width * s.height;
  }
}

console.log(area({ kind: 'rectangle', width: 3, height: 4 })); // 12

Checking the tag reveals the fields of that variant.

Interfaces & Types

Interfaces and aliases describe shapes checked structurally. They do not generate runtime validators or change the objects being described.

Compatibility normally depends on the members of a value. An object can satisfy an interface without explicitly naming it. Interfaces can merge declarations, while type aliases can name unions and other type expressions.

Name and extend object shapes

typescript
// Interface
interface User {
  readonly id: number;
  name: string;
  email?: string;    // optional
  greet(): string;
}

// Extending interface
interface Admin extends User {
  permissions: string[];
}

// Type alias
type Point = { x: number; y: number };
type ID = string | number;

An extending interface adds requirements to the base shape.

Describe dynamic keys and generic values

typescript
// Index signature
interface StringMap {
  [key: string]: string;
}

// Generic interface
interface Repository<T> {
  findById(id: number): Promise<T>;
  save(entity: T): Promise<T>;
  delete(id: number): Promise<void>;
}

An index signature constrains values accessed through dynamic keys.

Generics

Generics preserve relationships between inputs and outputs. Constraints specify capabilities without losing the caller's more precise type.

A generic parameter links positions in a signature. The caller’s argument can determine the return type. A constraint makes specific operations available inside the function while preserving the caller’s more specific type.

Infer and constrain type arguments

typescript
// Generic function
function identity<T>(value: T): T {
  return value;
}

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

// Constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

The key constraint ensures the property exists on the input type and preserves its value type.

Store typed values in a generic class

typescript
// Generic class
class Stack<T> {
  private items: T[] = [];
  push(item: T): void { this.items.push(item); }
  pop(): T | undefined { return this.items.pop(); }
  get size() { return this.items.length; }
}

const stack = new Stack<number>();
stack.push(42);
console.log(stack.pop(), stack.pop()); // 42 undefined

// Default type parameter
type ApiResponse<T = unknown> = {
  data: T;
  status: number;
  error?: string;
};

A class type argument determines which values the instance can store.

Functions

Function types describe parameters and results. Keep overloads consistent with implementations and remember that annotations disappear at runtime.

Parameter annotations constrain valid calls and a return annotation checks what the body produces. Optional parameters may be undefined inside the function. A default parameter supplies a value when the argument is omitted or undefined.

Type parameters and defaults

typescript
// Typed function
function add(a: number, b: number): number {
  return a + b;
}

// Optional & default
function greet(name: string, greeting?: string): string {
  return `${greeting ?? 'Hello'}, ${name}!`;
}

Omitted default arguments are supplied by the function.

Describe overloads and callable values

typescript
// Overloads
function format(value: string): string;
function format(value: number, decimals: number): string;
function format(value: string | number, decimals = 2): string {
  if (typeof value === 'string') return value.trim();
  return value.toFixed(decimals);
}

// Function type
type Predicate<T> = (value: T) => boolean;
const isPositive: Predicate<number> = n => n > 0;

// void and never
function log(msg: string): void { console.log(msg); }
function throwError(msg: string): never { throw new Error(msg); }

Each overload describes a supported call, and one implementation handles them.

Classes

Classes provide JavaScript behavior with additional static checks. TypeScript visibility modifiers have different runtime implications from JavaScript private fields.

Access modifiers describe which code may use a member. TypeScript private is checked by the compiler, while a field prefixed with a hash has JavaScript runtime privacy. A constructor parameter property declares and initializes a member in one step.

Extend a base class

typescript
class Animal {
  readonly id: number;
  name: string;
  #sound: string;   // private class field

  constructor(name: string, sound: string) {
    this.id = Math.random();
    this.name = name;
    this.#sound = sound;
  }

  speak(): string {
    return `${this.name} says ${this.#sound}`;
  }

  protected info(): string {
    return `Animal: ${this.name}`;
  }
}

Super initializes the base part before the derived class uses it.

Declare properties and abstract contracts

typescript
// Shorthand constructor parameters
class User {
  constructor(
    public name: string,
    private email: string,
    readonly createdAt: Date = new Date()
  ) {}
}

// Abstract class
abstract class Shape {
  abstract area(): number;
  toString() { return `Shape with area ${this.area()}`; }
}

Parameter properties declare and initialize members. Abstract members require a concrete implementation.

Utility Types

Utility types derive shapes such as optional properties or selected keys. They affect checking without copying or freezing runtime objects.

Utility types describe a derived view of an existing shape. Partial makes properties optional, and Pick selects keys. These types leave runtime objects untouched, so use ordinary code when you need to copy or remove properties.

Derive variants of an object shape

typescript
interface User {
  id: number;
  name: string;
  email: string;
  age?: number;
}

type UserDraft     = Partial<User>;           // all optional
type FullUser      = Required<User>;          // all required
type ImmutableUser = Readonly<User>;          // all readonly
type UserPreview   = Pick<User, 'id' | 'name'>;
type UserWithoutId = Omit<User, 'id'>;
type PageMap       = Record<string, User[]>;

Pick selects keys and Omit drops keys from the original shape.

Transform unions and function types

typescript
// Use User from the preceding example.
// Union manipulation
type NoNull  = Exclude<string | number | null, null>;
type Strings = Extract<string | number | boolean, string>;
type Safe    = NonNullable<string | null | undefined>;   // string

// Function types
function getUser() { return { id: 1, name: 'Alice' }; }
type UserReturn = ReturnType<typeof getUser>;
type AddParams  = Parameters<(a: number, b: number) => number>; // [number, number]
type UserData   = Awaited<Promise<User>>;

// Template literal utility
type EventName = 'click' | 'focus' | 'blur';
type Handler = `on${Capitalize<EventName>}`;   // 'onClick' | 'onFocus' | 'onBlur'

Extract selects matching members. ReturnType reads the result type of a callable.

Type Narrowing

Control-flow checks refine a value's type. Validate unknown external values before treating them as trusted application data.

A shared literal property can distinguish union alternatives. Each branch gains access to its matching fields; runtime input still needs validation before it enters this typed model.
flowchart TD
    Value["Validated union value"] --> Kind{"Check discriminant"}
    Kind -->|success| Success["Access success fields"]
    Kind -->|failure| Failure["Access failure fields"]
    Success --> Result["Return handled result"]
    Failure --> Result

The compiler follows runtime checks through each branch. For a tagged union, comparing the tag rules out variants with other tags and lets you read the fields of the surviving variant.

Narrow values with runtime checks

typescript
// typeof
function process(val: string | number) {
  if (typeof val === 'string') {
    return val.toUpperCase();
  }
  return val.toFixed(2);
}

// instanceof
function handleError(err: unknown) {
  if (err instanceof Error) {
    console.log(err.message);
  }
}

// in operator
type Cat = { meow(): void };
type Dog = { bark(): void };
function speak(animal: Cat | Dog) {
  if ('meow' in animal) animal.meow();
  else animal.bark();
}

The check determines which properties or methods are available inside a branch.

Reuse checks and verify exhaustiveness

typescript
// Type predicate
function isString(val: unknown): val is string {
  return typeof val === 'string';
}

// Exhaustiveness check
function assertNever(x: never): never {
  throw new Error(`Unhandled case: ${x}`);
}

A predicate exposes a reusable narrowing rule. Never checks for unhandled variants.

Decorators

Decorators attach behavior using the model supported by project configuration. Legacy experimental and standard decorators have different signatures and capabilities.

Decorator code runs as part of defining or initializing the decorated element. Confirm whether the fragment uses standard decorators or legacy experimental decorators, because their signatures and compiler settings differ.

Add behavior to a class

typescript
// Enable: 'experimentalDecorators': true in tsconfig

// Class decorator
function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
class BugReport {
  type = 'report';
  constructor(public title: string) {}
}

The legacy class decorator runs when the class is defined.

Wrap a method call

typescript
// Method decorator
function log(target: any, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;
  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${key}`);
    return original.apply(this, args);
  };
  return descriptor;
}

class Calculator {
  @log
  add(a: number, b: number) { return a + b; }
}

The legacy method decorator wraps the descriptor’s function. Use experimentalDecorators for both fragments.

tsconfig

tsconfig controls inputs, checks, module behavior, and output. Align settings with the runtime and bundler so accepted imports execute correctly.

Put the configuration in tsconfig.json and use tsc -p with the project directory. Match module resolution to the runtime or bundler that will load the output.

Configure a project build

json
{
  \"compilerOptions\": {
    \"target\": \"ES2022\",
    \"module\": \"ESNext\",
    \"moduleResolution\": \"bundler\",
    \"lib\": [\"ES2022\", \"DOM\"],
    \"outDir\": \"./dist\",
    \"rootDir\": \"./src\",
    \"strict\": true,
    \"noUncheckedIndexedAccess\": true,
    \"noImplicitOverride\": true,
    \"exactOptionalPropertyTypes\": true,
    \"skipLibCheck\": true,
    \"declaration\": true,
    \"sourceMap\": true,
    \"paths\": {
      \"@/*\": [\"./src/*\"]
    }
  },
  \"include\": [\"src\"],
  \"exclude\": [\"node_modules\", \"dist\"]
}

The compiler options control checking, module resolution and emitted output.

Check types without emitting JavaScript

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "noEmit": true
  },
  "include": [
    "src/**/*.ts"
  ]
}

Use this configuration when a separate build tool emits the JavaScript. Running tsc in the project checks types and writes no JavaScript files.

Mapped Types

Mapped types transform properties across a set of keys. Remapping and modifiers keep related API shapes synchronized without duplicating fields.

A mapped type iterates over a union of keys at compile time. Its value expression can look up the original property type, and modifiers determine whether the resulting property is optional or readonly.

Transform and remap keys

typescript
// Basic mapped type — iterate over all keys of T
type ReadonlyT<T>  = { readonly [K in keyof T]: T[K] };
type OptionalT<T>  = { [K in keyof T]?: T[K] };
type NullableT<T>  = { [K in keyof T]: T[K] | null };

// Remapping keys with 'as' (TS 4.1+)
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
// { getName: () => string; getAge: () => number; ... }

// Filtering keys with never
type OmitFunctions<T> = {
  [K in keyof T as T[K] extends Function ? never : K]: T[K];
};

Remapping can rename keys or remove them by producing never.

Change modifiers and recurse

typescript
// +readonly / -readonly   |   +? / -?
type Mutable<T>     = { -readonly [K in keyof T]: T[K] };
type AllRequired<T> = { [K in keyof T]-?: T[K] };

// DeepReadonly<T> — recursive mapped type
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};

// Literal union as key source
type Flags = { [K in 'a' | 'b' | 'c']: number };
// { a: number; b: number; c: number }

Mapped modifiers change optionality or mutability. Recursion applies the transformation to nested properties.

Conditional Types

Conditional types select results using assignability. A naked type parameter can distribute over a union, which changes how alternatives are transformed.

A conditional type selects a result based on assignability. A naked type parameter on the left of extends distributes over a union. Wrapping the checked types in tuples makes the test apply to the union as a whole.

Select types with a condition

typescript
// Basic: T extends U ? X : Y
type IsString<T> = T extends string ? true : false;
type A = IsString<'hello'>;   // true
type B = IsString<42>;        // false

// Distributive conditional types — distributes over union members
type ToArray<T> = T extends any ? T[] : never;
type C = ToArray<string | number>;   // string[] | number[]

// NonNullable reimplemented
type MyNonNullable<T> = T extends null | undefined ? never : T;
type D = MyNonNullable<string | null | undefined>;   // string

A naked type parameter distributes the conditional over each union member.

Unwrap types and control distribution

typescript
// Flatten<T> — unwrap one level of Array
type Flatten<T> = T extends Array<infer Item> ? Item : T;
type E = Flatten<string[]>;   // string
type F = Flatten<number>;     // number

// UnwrapPromise<T>
type UnwrapPromise<T> = T extends Promise<infer V> ? V : T;
type G = UnwrapPromise<Promise<string>>;   // string
type H = UnwrapPromise<boolean>;           // boolean

// Conditional return type in a generic function signature
declare function process<T>(val: T): T extends string ? string[] : number;

// Prevent distribution with a tuple wrapper
type NoDistribute<T> = [T] extends [string] ? true : false;
type I = NoDistribute<string | number>;   // false (not distributed)

Infer captures the inner type. A tuple wrapper checks the union as a whole.

infer & Type Inference

infer captures part of a matched type inside a conditional type. It extracts relationships such as function return types without runtime inspection.

Infer captures a type from the shape that matched. Extracting a function result captures the type after the arrow. The fallback branch handles types that do not match the function shape.

Extract parts of callable types

typescript
// ReturnType reimplemented with infer
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function greet() { return 'hello'; }
type A = MyReturnType<typeof greet>;   // string

// Parameters reimplemented with infer
type MyParameters<T> = T extends (...args: infer P) => any ? P : never;
function add(a: number, b: number) { return a + b; }
type B = MyParameters<typeof add>;   // [number, number]

// InstanceType
type MyInstanceType<T> = T extends new (...args: any[]) => infer R ? R : never;
class User { name = 'Alice'; }
type C = MyInstanceType<typeof User>;   // User

Infer binds the matching parameter list, return type or instance type.

Infer types from containers and pairs

typescript
// UnpackArray<T>
type UnpackArray<T> = T extends (infer U)[] ? U : T;
type D = UnpackArray<string[]>;   // string
type E = UnpackArray<number>;     // number

// Inferring from nested positions
type UnpackPromiseArray<T> = T extends Promise<(infer U)[]> ? U : never;
type F = UnpackPromiseArray<Promise<string[]>>;   // string

// Multiple infers in one conditional
type SwapArgs<T> = T extends (a: infer A, b: infer B) => infer R
  ? (a: B, b: A) => R
  : never;

declare function swap(a: number, b: string): boolean;
type G = SwapArgs<typeof swap>;   // (a: string, b: number) => boolean

A conditional can infer several positions independently from a matching input.

Template Literal Types

Template literal types construct string patterns from other types. They constrain names statically without validating arbitrary runtime text.

A template literal type combines known string pieces. When an interpolated position is a union, the compiler forms the possible combinations. Validate external strings before relying on that constraint at runtime.

Combine and transform literal strings

typescript
// Basic template literal type
type Greeting = `Hello, ${string}`;

// Combining unions — cartesian product of all combinations
type Color = 'red' | 'blue';
type Size  = 'sm' | 'lg';
type Class = `${Color}-${Size}`;
// 'red-sm' | 'red-lg' | 'blue-sm' | 'blue-lg'

// Built-in intrinsic string manipulation types
type U = Uppercase<'hello'>;      // 'HELLO'
type L = Lowercase<'HELLO'>;      // 'hello'
type C = Capitalize<'hello'>;     // 'Hello'
type N = Uncapitalize<'Hello'>;   // 'hello'

Interpolated unions generate combinations of their members.

Generate names and extract path parameters

typescript
// CamelToSnake via recursive template literal + infer
type CamelToSnake<S extends string> =
  S extends `${infer H}${infer T}`
    ? H extends Uppercase<H>
      ? `_${Lowercase<H>}${CamelToSnake<T>}`
      : `${H}${CamelToSnake<T>}`
    : S;
type Snake = CamelToSnake<'helloWorld'>;   // 'hello_world'

// Event handler name generation
type EventName = 'click' | 'focus' | 'blur';
type Handler = `on${Capitalize<EventName>}`;
// 'onClick' | 'onFocus' | 'onBlur'

// PathParams extraction
type ExtractParams<Path extends string> =
  Path extends `${string}:${infer Param}/${infer Rest}`
    ? Param | ExtractParams<`/${Rest}`>
    : Path extends `${string}:${infer Param}`
      ? Param
      : never;
type Params = ExtractParams<'/users/:id/posts/:postId'>;
// 'id' | 'postId'

Recursive matching consumes part of a string and continues on the remainder.

Modules & Namespaces

Modules use imports and exports as dependency boundaries. Namespaces group declarations differently; follow the runtime and build system's established convention.

Put separately labeled module fragments in separate files. An import type is erased during compilation, so it cannot supply a runtime value. A normal import can load an actual exported value.

Export values and types

typescript
// ES module imports / exports
import { helper } from './utils';
import defaultExport from './module';
export { helper };
export default function main() {}

// import type / export type — erased at compile time, zero runtime cost
import type { User } from './types';
export type { User };

// Namespace (legacy — prefer ES modules for new code)
namespace Validation {
  export interface StringValidator {
    isAcceptable(s: string): boolean;
  }
  export class LettersOnlyValidator implements StringValidator {
    isAcceptable(s: string) { return /^[A-Za-z]+$/.test(s); }
  }
}

A type-only import is erased and creates no runtime import.

Extend declarations across module boundaries

typescript
// Module augmentation — extend types from an external package
declare module 'express' {
  interface Request {
    user?: { id: number; name: string };
  }
}

// Ambient declarations (typically in a .d.ts file)
declare const __VERSION__: string;
declare function fetcher(url: string): Promise<Response>;

// declare global — extend global scope from a module file
declare global {
  interface Window {
    analytics: { track(event: string): void };
  }
}

// Triple-slash reference directive
/// <reference types='node' />

// paths alias — configured in tsconfig compilerOptions.paths
// import { x } from '@/utils';  resolves to ./src/utils

Augmentation changes the checker’s view of an existing module.

Advanced Patterns

Discriminated unions, brands, and builders model domain constraints. Pair static modeling with runtime validation for values entering from outside the program.

Use satisfies when you want to check that an expression meets a contract while retaining its inferred type. This keeps specific information available for later lookups.

Build values and preserve domain distinctions

typescript
// Builder pattern — fluent interface via method chaining
class QueryBuilder {
  private filters: string[] = [];
  private sortField = '';
  where(condition: string): this  { this.filters.push(condition); return this; }
  orderBy(field: string): this    { this.sortField = field; return this; }
  limit(n: number): this          { return this; }
  build(): string                 { return this.filters.join(' AND '); }
}
const q = new QueryBuilder().where('active = true').orderBy('name').limit(10).build();

// Branded / opaque types — prevent mixing structurally-identical primitives
type Opaque<T, Brand> = T & { readonly __brand: Brand };
type UserId  = Opaque<number, 'UserId'>;
type OrderId = Opaque<number, 'OrderId'>;
const uid = 1 as UserId;
// getUser(uid) ok   |   getUser(1 as OrderId) type error

// Exhaustive switch with assertNever
type Status = 'pending' | 'active' | 'closed';
function assertNever(x: never): never { throw new Error(`Unhandled: ${x}`); }
function handle(s: Status): string {
  switch (s) {
    case 'pending': return 'Waiting';
    case 'active':  return 'Running';
    case 'closed':  return 'Done';
    default:        return assertNever(s);
  }
}

A brand distinguishes otherwise compatible primitives at compile time.

Validate shapes and keep literal information

typescript
// satisfies operator (TS 4.9) — validate shape without widening
const palette = {
  red:   [255, 0, 0],
  green: '#00ff00',
} satisfies Record<string, string | number[]>;
palette.red;   // number[], not string | number[]

// as const — narrow to literal types
const config = { env: 'production', port: 3000 } as const;
// config.env is 'production', not string

// infer in template literals — extract string sub-parts
type GetParam<T extends string> =
  T extends `${string}:${infer P}` ? P : never;
type R = GetParam<'/user/:id'>;   // 'id'

Satisfies checks compatibility while retaining the inferred expression type.

Variance

TypeScript is structurally typed — variance emerges from how types are used, not declared. Return types are covariant (you can return a subtype), parameter types are contravariant (you must accept a supertype). The in/out modifiers (TS 4.7) make variance explicit and improve type-checking performance.

A producer can return a more specific type where a general result is expected. A consumer must accept every value the caller is allowed to pass. Check the parameter direction when assigning callbacks.

Compare inputs and outputs

typescript
// Covariance — T can be substituted with a subtype (output positions)
// Array<T> is covariant in T (TypeScript uses structural typing)
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs;   // OK — Dog extends Animal

// Function return types are covariant
type MakeDog    = () => Dog;
type MakeAnimal = () => Animal;
const f: MakeAnimal = (): Dog => new Dog();   // OK — covariant return

// Function parameter types are contravariant (opposite direction)
type EatDog    = (d: Dog)    => void;
type EatAnimal = (a: Animal) => void;
const g: EatDog = (a: Animal) => {};   // OK — contravariant param

A return value can be more specific. An accepted input must cover what callers can supply.

Apply variance to callback declarations

typescript
// Use the relevant declarations from the preceding example.
// Practical: callbacks
type Handler<T> = (event: T) => void;
// If MouseEvent extends Event:
declare const onMouse: Handler<MouseEvent>;
const onEvent: Handler<Event> = onMouse;   // Error — MouseEvent is narrower

// Bivariant method shorthand vs. strict function property (--strictFunctionTypes)
interface Container<T> {
    // method shorthand — bivariant (loose)
    transform(x: T): T;
    // property function — contravariant in param, covariant in return (strict)
    process: (x: T) => T;
}

// in/out annotations (TS 4.7) — explicit variance for better perf and clarity
type Provider<out T> = () => T;      // covariant     — T only produced
type Consumer<in T>  = (x: T) => void;  // contravariant — T only consumed

Under strictFunctionTypes, function properties check parameters more strictly than method declarations.

Declaration Files

Declaration files (.d.ts) are TypeScript's API description format — pure type information with no runtime code. They let you add types to untyped JavaScript libraries, extend third-party module interfaces, and declare ambient globals.

A declaration file describes the API the compiler should expect. It does not implement the module. Keep the declaration aligned with the JavaScript that will actually load.

Describe globals and untyped modules

typescript
// Declaration files (.d.ts) describe the shape of JS modules for TypeScript.
// You never ship .d.ts to users — TypeScript uses them at compile time only.

// ── Ambient variable declarations ─────────────────────────────────────────
declare const __VERSION__: string;
declare function fetcher(url: string): Promise<Response>;
declare class EventEmitter {
    on(event: string, cb: (...args: unknown[]) => void): this;
    emit(event: string, ...args: unknown[]): boolean;
}

// ── Module declaration — typed stub for an untyped JS package ─────────────
// file: types/some-legacy-lib.d.ts
declare module 'some-legacy-lib' {
    export interface Options { timeout?: number; retries?: number; }
    export function fetch(url: string, opts?: Options): Promise<string>;
    export const version: string;
    export default function init(): void;
}

A declaration describes an existing runtime value without implementing it.

Augment existing declarations

typescript
// ── Global augmentation — extend the global scope ─────────────────────────
declare global {
    interface Window {
        analytics: { track(event: string, props?: object): void };
    }
    interface Array<T> {
        last(): T | undefined;
    }
}

// ── Module augmentation — extend a third-party module ─────────────────────
import 'express';
declare module 'express' {
    interface Request {
        user?: { id: number; email: string };
        requestId: string;
    }
}

// ── Triple-slash directives ────────────────────────────────────────────────
/// <reference types='node' />          // pulls in @types/node globals
/// <reference path='./extra.d.ts' />   // includes another .d.ts file
/// <reference lib='dom' />             // enables DOM lib without tsconfig change

Global and module augmentations merge into declarations already visible to the checker.

Recursive Types

Recursive type aliases reference themselves to model JSON, tree structures, deeply-nested configurations, and path extraction. TypeScript limits recursion depth to prevent infinite loops during compilation — use interface for recursive object types when possible, as they resolve lazily.

Start with the base case and identify what gets smaller on each step. Deep or broadly branching recursion increases the amount of work the compiler must perform.

Model nested data

typescript
// JSON — a value can be any JSON type, including nested
type Json =
    | null
    | boolean
    | number
    | string
    | Json[]
    | { [key: string]: Json };

const data: Json = { name: 'Alice', scores: [1, 2, [3, 4]], active: true };

// Recursive tree
type TreeNode<T> = {
    value: T;
    children: TreeNode<T>[];
};

The type can refer to itself through an object or array member.

Transform nested properties and paths

typescript
// Deep partial — recursively make all properties optional
type DeepPartial<T> = T extends object
    ? { [K in keyof T]?: DeepPartial<T[K]> }
    : T;

// Deep readonly — recursively make all properties readonly
type DeepReadonly<T> = T extends (infer U)[]
    ? ReadonlyArray<DeepReadonly<U>>
    : T extends object
        ? { readonly [K in keyof T]: DeepReadonly<T[K]> }
        : T;

// Flatten nested array one level
type Flatten<T> = T extends (infer U)[] ? U : T;

// Path extraction — all dot-separated key paths in an object
// (uses conditional string concat to avoid nested template literals)
type Dot<D extends string, K extends string> =
    D extends '' ? K : `${D}.${K}`;

type Paths<T, D extends string = ''> = {
    [K in keyof T & string]:
        T[K] extends object
            ? Paths<T[K], Dot<D, K>>
            : Dot<D, K>;
}[keyof T & string];

type Config = { db: { host: string; port: number }; debug: boolean };
type ConfigPaths = Paths<Config>;   // 'db.host' | 'db.port' | 'debug'

A recursive mapped type applies the same rule to nested properties.

Assertion Functions

An assertion function has the return type asserts condition or asserts x is T. After a successful call TypeScript narrows the type in the subsequent code, exactly like a type guard — but by throwing on failure rather than returning false.

The signature tells the compiler what is true after a successful return. The body must throw when that claim fails. Returning normally after invalid input makes later code trust a false claim.

Assert a condition before use

typescript
// Assertion function — throws if condition is false; narrows type afterward
function assert(condition: unknown, msg: string): asserts condition {
    if (!condition) throw new Error(msg);
}

function assertDefined<T>(val: T, msg = 'Expected defined value'): asserts val is NonNullable<T> {
    if (val === null || val === undefined) throw new Error(msg);
}

// Usage — TypeScript narrows after the assertion call
function process(val: string | null) {
    assertDefined(val, 'val must not be null');
    val.toUpperCase();   // OK — val is string here
}

When the function returns normally, the checker assumes the asserted condition holds.

Assert a specific type or unreachable branch

typescript
// Use the relevant declarations from the preceding example.
// Assertion function as a type predicate
function isString(val: unknown): asserts val is string {
    if (typeof val !== 'string') throw new TypeError(`Expected string, got ${typeof val}`);
}

// Use in tests (e.g. Vitest / Jest)
function assertDeepEqual<T>(a: T, b: T): asserts a is T {
    if (JSON.stringify(a) !== JSON.stringify(b))
        throw new Error(`Expected ${JSON.stringify(a)} to equal ${JSON.stringify(b)}`);
}

// assertNever — exhaustiveness guard
type Status = 'open' | 'closed' | 'pending';
function assertNever(x: never): never {
    throw new Error(`Unhandled case: ${JSON.stringify(x)}`);
}

function describeStatus(s: Status): string {
    switch (s) {
        case 'open':    return 'Open';
        case 'closed':  return 'Closed';
        case 'pending': return 'Pending';
        default:        return assertNever(s);   // type error if a case is missing
    }
}

A typed assertion narrows its argument. An assertNever call exposes a missing case.

const Type Parameters

The const modifier on a type parameter (TS 5.0) infers the literal type of an argument without requiring as const at the call site. The satisfies operator (TS 4.9) validates that a value matches a type while preserving the most specific inferred type.

A const type parameter asks inference to preserve literal detail for an argument expression. Give it a compatible readonly constraint when preserving tuple elements matters. A value already widened before the call cannot recover its original literal types.

Infer literals from arguments

typescript
// const type parameters (TS 5.0) — infer literal types without 'as const'
function identity<const T>(x: T): T { return x; }

identity([1, 2, 3]);        // type is readonly [1, 2, 3], not number[]
identity({ a: 1, b: 2 });   // type is { readonly a: 1; readonly b: 2 }

// Compare without const — types are widened
function widened<T>(x: T): T { return x; }
widened([1, 2, 3]);          // type is number[]
widened({ a: 1 });           // type is { a: number }

// Practical: route builder with literal path inference
function route<const Path extends string>(path: Path) {
    return { path, match: (s: string) => s === path };
}
const r = route('/users/:id');
r.path;   // type is '/users/:id', not string

A const type parameter can retain literal inference for inline arguments.

Check an object and scope resource cleanup

typescript
// satisfies operator (TS 4.9) — validate type without widening
const palette = {
    red:   [255, 0, 0],
    green: '#00ff00',
    blue:  [0, 0, 255],
} satisfies Record<string, string | number[]>;

palette.red;    // type is number[], not string | number[]
palette.green;  // type is string,   not string | number[]

// using declaration (TS 5.2) — Symbol.dispose / Symbol.asyncDispose
class DbConnection {
    [Symbol.dispose]() { console.log('closing connection'); }
}

function query() {
    using conn = new DbConnection();
    // conn is automatically disposed when the block exits
    return 'results';
}

Satisfies checks the shape. A using declaration invokes disposal at scope exit.

keyof, typeof & Indexed Access

keyof T extracts a union of all keys of a type, typeof x captures the compile-time type of a value, and indexed access types (T[K]) let you look up the type of any property. Together they form the backbone of type-safe property access, array element inference, and mapped-type key remapping.

Use typeof in a type position to describe an existing value’s type. Keyof gets its allowed keys, and indexed access retrieves the type at a key. Combining them keeps a lookup signature aligned with its input object.

Select properties by valid keys

typescript
// keyof — produces a union of all keys of a type
type User = { id: number; name: string; email: string };
type UserKey = keyof User;   // 'id' | 'name' | 'email'

// typeof — capture the type of a value
const config = { host: 'localhost', port: 5432 } as const;
type Config = typeof config;
// { readonly host: 'localhost'; readonly port: 5432 }

// Indexed access types — T[K] looks up a property type
type IdType   = User['id'];           // number
type NameType = User['name'];         // string
type AnyValue = User[keyof User];     // number | string

// Combine keyof + generics for type-safe property access
function getField<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
const nameVal = getField({ id: 1, name: 'Alice' }, 'name');   // string

Keyof constrains keys and indexed access gives the corresponding value type.

Extract element and nested types

typescript
// Use the relevant declarations from the preceding example.
// Array element type
const roles = ['admin', 'editor', 'viewer'] as const;
type Role = typeof roles[number];   // 'admin' | 'editor' | 'viewer'

// Nested indexed access
type DeepProp = {
  user: { address: { city: string; zip: number } };
};
type CityType = DeepProp['user']['address']['city'];   // string

// keyof with mapped types — transforms each key
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Booleans<T> = { [K in keyof T]: boolean };

// Narrowing with keyof
function hasKey<T extends object>(obj: T, key: PropertyKey): key is keyof T {
  return key in obj;
}

// ReturnType via indexed access
interface Actions {
  fetch(): Promise<User[]>;
  save(u: User): Promise<void>;
}
type FetchReturn = ReturnType<Actions['fetch']>;   // Promise<User[]>

Indexing an array type with number retrieves its element type.

This is commonly called the const-array-to-union pattern, or deriving a literal union from a const array. For a value-derived union, first use as const to keep each array entry as its exact literal type instead of widening them all to string. Then typeof roles gets the tuple type, and indexing it with [number] means “any element at a numeric index,” producing 'admin' | 'editor' | 'viewer'.

This keeps a runtime list and its type in one place: update the array and the union updates automatically. It is useful for fixed sets such as asset rarities, roles, statuses, and configuration options.

Function Overloads & this

TypeScript supports multiple call signatures for the same function or method, allowing the return type to depend on the argument types. The explicit this parameter enforces the receiver type inside methods and callbacks, while polymorphic this preserves the concrete subclass type through fluent builder chains.

Callers see the overload signatures. The implementation must handle each declared shape. A this parameter describes the required receiver and is erased from the emitted parameter list.

Offer several call signatures

typescript
// Function overloads — multiple signatures, one implementation
function parse(input: string): number;
function parse(input: number): string;
function parse(input: string | number): string | number {
  if (typeof input === 'string') return parseInt(input, 10);
  return input.toString();
}

const a = parse('42');   // number
const b = parse(99);     // string

// Method overloads on a class
class Formatter {
  format(value: string): string;
  format(value: number, decimals: number): string;
  format(value: string | number, decimals = 2): string {
    if (typeof value === 'string') return value.trim();
    return value.toFixed(decimals);
  }
}

Callers see overload signatures. The implementation handles all supported calls.

Type receivers and fluent return values

typescript
// this parameter — explicit type for the receiver
interface Counter {
  count: number;
  increment(this: Counter): Counter;
}
const counter: Counter = {
  count: 0,
  increment() { this.count++; return this; },
};

// this in callbacks — prevent accidental detachment
class Button {
  label = 'Click me';
  handleClick(this: Button): void {
    console.log(this.label);   // 'this' is always Button
  }
}

// Polymorphic this — enables fluent interfaces on subclasses
class Builder {
  protected config: Record<string, unknown> = {};
  set(key: string, value: unknown): this { this.config[key] = value; return this; }
}
class AdvancedBuilder extends Builder {
  validate(): this { return this; }
}
const result = new AdvancedBuilder().set('a', 1).validate().set('b', 2);

// Call signatures on object types
interface Multiplier {
  (factor: number): number;
  base: number;
}
const triple = Object.assign((f: number) => 3 * f, { base: 3 }) as Multiplier;

An explicit this parameter checks the receiver. A polymorphic this result preserves a subclass type.

Error Types & Result Pattern

Typed error hierarchies replace stringly-typed error codes with structured, narrowable classes. The Result / Either pattern wraps fallible operations in a discriminated union so callers must handle both success and failure paths without try/catch, making error flows explicit in the type system.

A result union makes callers examine success and failure explicitly. Narrow on its tag before reading the value or error payload. Use the failure branch for outcomes the caller can reasonably handle.

Classify thrown errors

typescript
// Typed error hierarchy
class AppError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly statusCode = 500
  ) {
    super(message);
    this.name = 'AppError';
  }
}

class NotFoundError extends AppError {
  constructor(resource: string, id: string | number) {
    super(`${resource} ${id} not found`, 'NOT_FOUND', 404);
    this.name = 'NotFoundError';
  }
}

class ValidationError extends AppError {
  constructor(
    public readonly field: string,
    message: string
  ) {
    super(message, 'VALIDATION_ERROR', 400);
    this.name = 'ValidationError';
  }
}

An error subclass lets a handler recognize a specific failure category.

Return and consume typed results

typescript
// Result / Either pattern — no-throw error handling
type Ok<T>  = { ok: true;  value: T };
type Err<E> = { ok: false; error: E };
type Result<T, E = AppError> = Ok<T> | Err<E>;

function ok<T>(value: T): Ok<T>   { return { ok: true,  value }; }
function err<E>(error: E): Err<E> { return { ok: false, error }; }

async function findUser(id: number): Promise<Result<{ id: number; name: string }>> {
  if (id <= 0) return err(new ValidationError('id', 'id must be positive'));
  const user = await fetch(`/api/users/${id}`).then(r => r.json()).catch(() => null);
  if (!user) return err(new NotFoundError('User', id));
  return ok(user);
}

// Consuming a Result
const res = await findUser(1);
if (res.ok) {
  console.log(res.value.name);
} else {
  if (res.error instanceof NotFoundError) {
    console.error('404:', res.error.message);
  } else {
    console.error('Error:', res.error.code);
  }
}

// catch type — always unknown in strict mode
try {
  JSON.parse('bad json');
} catch (e: unknown) {
  if (e instanceof SyntaxError) console.error(e.message);
}

The discriminant selects the success value or error field.

Advanced Generic Patterns

Variadic tuple types enable type-safe argument spreading and concatenation. Curried generic functions carry full type information across partial applications. Phantom (tagged) types prevent mixing structurally identical values, and recursive conditionals extract deep leaf types — all without any runtime overhead.

Preserve the relationship that callers need. For property lookups, relate the key to the object type and derive the result from that key. An unrelated generic cannot express the same guarantee.

Preserve tuple positions

typescript
// Variadic tuple types (TS 4.0+) — spread in tuple positions
type Concat<A extends unknown[], B extends unknown[]> = [...A, ...B];
type Pair = Concat<[string], [number]>;   // [string, number]

function concat<A extends unknown[], B extends unknown[]>(a: A, b: B): [...A, ...B] {
  return [...a, ...b];
}
const combined = concat([1, 'hello'] as const, [true] as const);   // [1, 'hello', true]

// Partial application at the type level
type Curry<F> = F extends (a: infer A, b: infer B) => infer R
  ? (a: A) => (b: B) => R
  : never;

function curry<A, B, R>(f: (a: A, b: B) => R): (a: A) => (b: B) => R {
  return a => b => f(a, b);
}
const add = curry((a: number, b: number) => a + b);
const add5 = add(5);   // (b: number) => number
add5(3);   // 8

Tuple spreads represent the remaining parameters after partial application.

Collect nested types and compose transformations

typescript
// Recursive conditional — collect leaf types
type Leaves<T> = T extends object
  ? { [K in keyof T]: Leaves<T[K]> }[keyof T]
  : T;
type Flat = Leaves<{ a: { b: string; c: number }; d: boolean }>;   // string | number | boolean

// Phantom type — attach a type tag without runtime overhead
declare const __brand: unique symbol;
type Tagged<T, Tag extends string> = T & { readonly [__brand]: Tag };
type MetersT  = Tagged<number, 'Meters'>;
type SecondsT = Tagged<number, 'Seconds'>;

const dist = 100 as MetersT;
const time = 10  as SecondsT;
// const bad: MetersT = time;   // Error — different tags

// Generic pipeline — compose transformations with inferred types
function pipe<A>(a: A): A;
function pipe<A, B>(a: A, f1: (a: A) => B): B;
function pipe<A, B, C>(a: A, f1: (a: A) => B, f2: (b: B) => C): C;
function pipe(value: unknown, ...fns: Array<(v: unknown) => unknown>): unknown {
  return fns.reduce((v, f) => f(v), value);
}
const out = pipe('  hello  ', s => (s as string).trim(), s => (s as string).toUpperCase());

Recursion collects leaf types. A pipeline passes one transformation’s output to the next.

Advanced Type Guards

Beyond simple typeof and instanceof, TypeScript supports structural duck-typing predicates, composable guard combinators, and array-of-T guards. Coupling these with discriminated unions and assertNever achieves fully exhaustive, type-safe branching across complex domain models.

A type predicate narrows the value when it returns true. Test the fields that justify the predicate. A guard that checks only one field cannot justify stronger claims about unverified fields.

Check tagged and structural shapes

typescript
// Discriminated union guard with exhaustiveness
type Shape =
  | { kind: 'circle';    radius: number }
  | { kind: 'rect';      w: number; h: number }
  | { kind: 'triangle';  base: number; height: number };

function assertNever(x: never): never { throw new Error(`Unhandled: ${JSON.stringify(x)}`); }

function area(s: Shape): number {
  switch (s.kind) {
    case 'circle':   return Math.PI * s.radius ** 2;
    case 'rect':     return s.w * s.h;
    case 'triangle': return (s.base * s.height) / 2;
    default:         return assertNever(s);
  }
}

// Structural predicate — duck-typing check
function hasFields<T extends object>(
  val: unknown,
  ...keys: (keyof T)[]
): val is T {
  return typeof val === 'object' && val !== null &&
    keys.every(k => k in (val as object));
}

interface ApiUser { id: number; name: string; email: string }
const data: unknown = JSON.parse('{}');
if (hasFields<ApiUser>(data, 'id', 'name', 'email')) {
  data.name.toUpperCase();   // safe
}

A structural guard inspects the fields that its predicate promises.

Validate items and combine predicates

typescript
// Use the relevant declarations from the preceding example.
// Assertion-style guard that throws
function assertShape<T>(
  val: unknown,
  guard: (v: unknown) => v is T,
  msg: string
): asserts val is T {
  if (!guard(val)) throw new TypeError(msg);
}

// Guarding arrays
function isArrayOf<T>(arr: unknown, guard: (v: unknown) => v is T): arr is T[] {
  return Array.isArray(arr) && arr.every(guard);
}
const isString = (v: unknown): v is string => typeof v === 'string';
const tags: unknown = ['a', 'b', 'c'];
if (isArrayOf(tags, isString)) tags.forEach(t => t.toUpperCase());

// Compose predicates
const and = <T>(g1: (v: unknown) => v is T, g2: (v: T) => boolean) =>
  (v: unknown): v is T => g1(v) && g2(v);
const isNonEmptyString = and(isString, s => s.length > 0);

Test elements before claiming an array’s item type.

Class Patterns & Mixins

Mixin factories compose independent behaviours (timestamping, activation, serialisation) onto any base class without deep inheritance chains. Private class fields (#field) enforce true encapsulation, and static factory methods validate invariants before construction — a pattern that replaces constructors for value-object types.

A mixin builds a class around an input constructor. Its constraint records the capabilities its implementation needs. Instances of the result retain the base behavior and gain the added methods.

Compose class behavior

typescript
// Mixin factory — compose behaviours without deep inheritance
type Constructor<T = {}> = new (...args: unknown[]) => T;

function Timestamped<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    createdAt = new Date();
    updatedAt = new Date();
    touch() { this.updatedAt = new Date(); }
  };
}

function Activatable<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    active = false;
    activate()   { this.active = true; }
    deactivate() { this.active = false; }
  };
}

class Entity {
  constructor(public id: number) {}
}

const TimestampedActivatableEntity = Activatable(Timestamped(Entity));
class User extends TimestampedActivatableEntity {
  constructor(id: number, public name: string) { super(id); }
}

const u = new User(1, 'Alice');
u.activate();
u.touch();

// Abstract mixin for serialisation
function Serializable<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    toJSON(): string { return JSON.stringify(this); }
  };
}

A mixin returns a class that extends its supplied base.

Control construction and private state

typescript
// Private fields + static factories
class Money {
  readonly #amount: number;
  readonly #currency: string;

  private constructor(amount: number, currency: string) {
    this.#amount = amount;
    this.#currency = currency;
  }

  static of(amount: number, currency: string): Money {
    if (amount < 0) throw new RangeError('amount must be >= 0');
    return new Money(amount, currency);
  }

  add(other: Money): Money {
    if (this.#currency !== other.#currency) throw new Error('currency mismatch');
    return Money.of(this.#amount + other.#amount, this.#currency);
  }

  toString(): string { return `${this.#amount} ${this.#currency}`; }
}

A static factory controls creation. Private fields restrict direct access to internal state.

Nominal & Opaque Types

TypeScript's structural typing lets two types with identical shapes unify silently. Branded types attach a phantom unique symbol tag to a primitive so the compiler treats UserId and OrderId as distinct — preventing accidental swaps at zero runtime cost. Validation constructors enforce domain invariants at the only place raw values enter the system.

A brand distinguishes values that share a runtime representation, such as two kinds of IDs. Build branded values at a validated boundary, because the brand alone adds no runtime check.

Distinguish structurally identical values

typescript
// Structural typing pitfall — two types with same shape are interchangeable
type Meters  = number;
type Seconds = number;
function speed(d: Meters, t: Seconds): number { return d / t; }
speed(100, 9.58);       // OK — but swapping args silently compiles too

// Branded / opaque types — attach a phantom brand to prevent mixing
declare const __brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [__brand]: B };

type MetersB  = Brand<number, 'Meters'>;
type SecondsB = Brand<number, 'Seconds'>;

function toMeters(n: number): MetersB   { return n as MetersB; }
function toSeconds(n: number): SecondsB { return n as SecondsB; }

function speedB(d: MetersB, t: SecondsB): number { return d / t; }
const dm = toMeters(100);
const tm = toSeconds(9.58);
speedB(dm, tm);         // OK
// speedB(tm, dm);      // Error — types are incompatible

// UserId / OrderId — prevent accidental ID swaps
type UserId  = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;

function getUser(id: UserId): Promise<{ name: string }> {
  return fetch(`/users/${id}`).then(r => r.json());
}

const uid   = 'u-123' as UserId;
const oid   = 'o-456' as OrderId;
getUser(uid);     // OK
// getUser(oid);  // Error

A brand makes values with different domain meanings incompatible at compile time.

Validate before applying a brand

typescript
// Use the relevant declarations from the preceding example.
// Validation constructor — ensures invariants at the boundary
class EmailAddress {
  private constructor(public readonly value: string) {}
  static parse(raw: string): EmailAddress {
    if (!/^[^@]+@[^@]+\.[^@]+$/.test(raw)) throw new Error('invalid email');
    return new EmailAddress(raw);
  }
}

// Safe integer — proof-carrying type
type SafeInt = Brand<number, 'SafeInt'>;
function safeInt(n: number): SafeInt {
  if (!Number.isSafeInteger(n)) throw new RangeError('not a safe integer');
  return n as SafeInt;
}

The validation constructor checks the runtime invariant before returning the branded value.

Type-Level Testing

The Expect / Equal / NotEqual helpers turn compile-time type assertions into ordinary variables: if a type assertion is wrong, the file fails to compile. This technique, popularised by the tsd and type-challenges projects, lets you write a full test suite for your utility types alongside your source code.

Run the compiler to check these assertions. An expected error directive should cover a deliberately invalid case. If that case stops producing an error, the unused directive makes the regression visible.

Assert expected types

typescript
// Type-level test helpers — assert type relationships at compile time
type Expect<T extends true> = T;
type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
type NotEqual<A, B> = Equal<A, B> extends true ? false : true;
type Extends<A, B> = A extends B ? true : false;
type IsNever<T> = [T] extends [never] ? true : false;

// Usage — if any of these produce a type error, the type is wrong
type _tests = [
  Expect<Equal<ReturnType<() => string>, string>>,
  Expect<Equal<Awaited<Promise<number>>, number>>,
  Expect<NotEqual<string, number>>,
  Expect<Extends<'hello', string>>,
  Expect<IsNever<never>>,
];

// Testing a custom DeepPartial utility type
type DeepPartial<T> = T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;
type _dp = [
  Expect<Equal<DeepPartial<{ a: number }>, { a?: number }>>,
  Expect<Equal<DeepPartial<{ a: { b: string } }>, { a?: { b?: string } }>>,
];

A test helper fails compilation when the inferred type differs from the expectation.

Test distribution and assignability

typescript
// Use the relevant declarations from the preceding example.
// Asserting on conditional type distribution
type ToArray<T> = T extends unknown ? T[] : never;
type _ta = [
  Expect<Equal<ToArray<string | number>, string[] | number[]>>,
];

// Checking mapped type output — template literal keys
type EventMap = { click: MouseEvent; focus: FocusEvent };
type Handlers = { [K in keyof EventMap as `on${Capitalize<string & K>}`]: (e: EventMap[K]) => void };
type HasOnClick = 'onClick' extends keyof Handlers ? true : false;
const _h: Expect<Equal<HasOnClick, true>> = true;
// @ts-expect-error — onBlur is absent from Handlers
const missing: keyof Handlers = 'onBlur';

// Checking assignability
type Assign<A, B> = A extends B ? B extends A ? true : false : false;
const _str: Expect<Equal<Assign<string, string>, true>> = true;
const _dif: Expect<Equal<Assign<string, number>, false>> = true;

// Verify optional fields survive Partial / Required roundtrip
type WithOptional = { a: string; b?: number };
type Keys = keyof Required<WithOptional>;
const _keys: Expect<Equal<Keys, 'a' | 'b'>> = true;

Check transformed keys and union members. An expected-error directive also fails if the error disappears.

Performance & Type Complexity

Complex generic types can dramatically slow the TypeScript compiler. Key rules: prefer lazy interfaces over eager type aliases for recursive shapes; avoid wide string unions where Record<string, T> suffices; extract repeated conditional checks into named aliases so the compiler can cache instantiations; and use tsc --diagnostics to measure instantiation counts and identify bottlenecks.

Measure checking time before simplifying types. Large unions can multiply through distribution and recursion can amplify that work. Name intermediate types so readers can understand the intended steps.

Limit expansion in complex types

typescript
// Eager vs. lazy resolution
// Interfaces resolve lazily — better for recursive types and large unions
interface LazyNode { value: number; children: LazyNode[] }   // OK

// Type aliases resolve eagerly — guard self-references with a conditional
// type Cycle = { children: Cycle[] }   // may slow down the checker

// Avoid wide union explosion — each member multiplies checking work
// Prefer Record/index signatures for open-ended key sets
type ColorMap = Record<string, string>;   // fast O(1) lookup

// Prefer single conditional over nested chain
// Slow: T extends A ? X : T extends B ? X : T extends C ? X : never
// Fast: T extends A | B | C ? X : never
type IsJsonPrimitive<T> = T extends string | number | boolean | null ? true : false;

// Extract reused conditionals to named aliases — compiler caches them
type IsObject<T> = T extends object ? true : false;
type Deep<T> = IsObject<T> extends true ? { [K in keyof T]: Deep<T[K]> } : T;

Union expansion can multiply the work done by a conditional type.

Check indexing and measure compiler work

typescript
// noUncheckedIndexedAccess — catches missing bounds checks
// (set in tsconfig: 'noUncheckedIndexedAccess': true)
const arr: number[] = [1, 2, 3];
const first: number | undefined = arr[0];   // undefined with the flag

// Prefer unknown over any — keeps the type checker engaged
function safeParse(json: string): unknown {
  return JSON.parse(json);
}

// satisfies for literal inference without type widening
const routes = {
  home:    '/',
  about:   '/about',
  contact: '/contact',
} satisfies Record<string, string>;
routes.home;   // type is '/', not string

// Use type guards instead of as casts for safe narrowing
function asString(val: unknown): string {
  if (typeof val !== 'string') throw new TypeError('expected string');
  return val;   // narrowed — no assertion needed
}

// Measure instantiation depth with tsc --diagnostics
// High 'Instantiation count'  → simplify recursive or distributive types
// High 'Check time'           → reduce union member count or inline helpers

Unchecked indexes may be missing. Compiler diagnostics help quantify the cost of type instantiation.

TypeScript Compiler API

The typescript package exposes a full compiler API for building codemods, linters, documentation generators, and custom transforms. You can parse source text into an AST, walk nodes with forEachChild, query types through the TypeChecker, and emit transformed output via a custom TransformerFactory — all programmatically, without shelling out to tsc.

Use the TypeScript package in a Node project. Parse a source file to inspect syntax. Create a program and use its type checker when the analysis needs resolved symbols or types.

Inspect syntax and type information

typescript
// TypeScript Compiler API — programmatic access to the TS compiler
import ts from 'typescript';

// 1. Parse a source file into an AST
const source = ts.createSourceFile(
  'example.ts',
  'const x: number = 42;',
  ts.ScriptTarget.Latest,
  true
);

// 2. Walk the AST
function visit(node: ts.Node, depth = 0): void {
  const indent = '  '.repeat(depth);
  console.log(`${indent}${ts.SyntaxKind[node.kind]}`);
  ts.forEachChild(node, child => visit(child, depth + 1));
}
visit(source);

// 3. Create a Program and type-check
const host = ts.createCompilerHost({ strict: true });
const program = ts.createProgram(['./src/index.ts'], { strict: true }, host);
const checker = program.getTypeChecker();
const diagnostics = ts.getPreEmitDiagnostics(program);
diagnostics.forEach(d => {
  const msg = ts.flattenDiagnosticMessageText(d.messageText, '\\n');
  if (d.file && d.start !== undefined) {
    const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
    console.error(`${d.file.fileName}(${line + 1},${character + 1}): ${msg}`);
  } else {
    console.error(msg);
  }
});

// 4. Extract type info with the checker
function getNodeType(node: ts.Node): string {
  const type = checker.getTypeAtLocation(node);
  return checker.typeToString(type);
}

A source file provides syntax nodes. The program’s checker resolves types in context.

Transform nodes and emit output

typescript
// Use the relevant declarations from the preceding example.
// 5. Custom transformer — add readonly to all class properties
function addReadonlyTransformer(context: ts.TransformationContext) {
  return (rootNode: ts.SourceFile) => {
    function visitNode(node: ts.Node): ts.Node {
      if (ts.isPropertyDeclaration(node)) {
        const mods = [ts.factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)];
        return ts.factory.updatePropertyDeclaration(
          node, mods, node.name, node.questionToken, node.type, node.initializer
        );
      }
      return ts.visitEachChild(node, visitNode, context);
    }
    return ts.visitNode(rootNode, visitNode) as ts.SourceFile;
  };
}

// 6. Emit transformed output
const transformResult = ts.transform(source, [addReadonlyTransformer]);
const printer = ts.createPrinter();
const output = printer.printFile(transformResult.transformed[0]);
console.log(output);
transformResult.dispose();

A transformer produces updated nodes before emission.

Best Practices

Type Design

Model valid states and avoid assertions that hide uncertainty. unknown forces callers to establish an external value's shape before use.

Model valid states directly. A tagged union can pair each state with the fields that exist in that state, which lets consumers handle cases exhaustively.

Choose a representation for each shape

typescript
// Prefer interfaces for object shapes (lazy resolution, better error messages)
interface User {
  readonly id: string;    // readonly — immutable after creation
  name: string;
  email: string;
}

// Use type for unions, intersections, and aliases
type ID = string | number;
type AdminUser = User & { permissions: string[] };

// Avoid any — use unknown and narrow instead
function processInput(val: unknown): string {
  if (typeof val === 'string') return val.toUpperCase();
  if (typeof val === 'number') return val.toFixed(2);
  throw new TypeError('unsupported input type');
}

Interfaces describe object contracts and aliases can name unions.

Encode valid variants and domain IDs

typescript
// Use never to enforce exhaustiveness
type Shape = { kind: 'circle'; r: number } | { kind: 'rect'; w: number; h: number };
function area(s: Shape): number {
  switch (s.kind) {
    case 'circle': return Math.PI * s.r ** 2;
    case 'rect':   return s.w * s.h;
    default:       throw new Error('unhandled shape: ' + (s as never));
  }
}

// Const assertions — preserve literal types
const CONFIG = { env: 'production', port: 3000 } as const;

// Prefer discriminated unions over optional fields
type Result<T, E = Error> =
  | { ok: true;  value: T }
  | { ok: false; error: E };

// Branded types for domain IDs
declare const __brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [__brand]: B };
type UserId  = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;

A discriminant narrows variants and a brand keeps domain identifiers distinct.

Generics & Utilities

Add type parameters when they preserve a real API relationship. Utilities should reduce duplication without making diagnostics difficult to understand.

A type parameter earns its place when it relates inputs or outputs. Prefer a concrete type for independent values, and let inference fill in the type argument when the call makes it clear.

Constrain reusable types

typescript
// Constrain with extends before using
function getField<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Provide default type params for common cases
type ApiResponse<T = unknown> = { data: T; status: number; error?: string };

// Use built-in utility types — avoid reinventing them
type UserDraft    = Partial<User>;
type ImmUser      = Readonly<User>;
type UserPreview  = Pick<User, 'id' | 'name'>;
type UserInput    = Omit<User, 'id'>;
type RoleMap      = Record<string, string[]>;

Constraints let the implementation rely on specific members of its inputs.

Document and name generic relationships

typescript
// Extract a generic only when it is used in 3+ places
type Paginated<T> = { items: T[]; total: number; page: number; pageSize: number };

// Keep generic names meaningful
interface Repository<TEntity> {
  findById(id: string): Promise<TEntity | null>;
  save(entity: TEntity): Promise<TEntity>;
  delete(id: string): Promise<void>;
}

// Conditional types for type-level logic
type Flatten<T> = T extends Array<infer Item> ? Item : T;
type Awaited2<T> = T extends Promise<infer V> ? Awaited2<V> : T;

// Document expected constraints in JSDoc
/**
 * Sorts items by a numeric or string key.
 * @typeParam TItem - must have a comparable key K
 */
function sortBy<TItem, K extends keyof TItem>(
  items: TItem[],
  key: K
): TItem[] {
  return [...items].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0));
}

Name parameters after their role and document the assumptions callers must meet.

Narrowing & Guards

Use discriminants and focused guards to refine alternatives. A custom predicate promises a type to the checker, so its checks must establish that claim.

Validate values entering as unknown before using their fields. Branch on evidence from runtime checks, so the narrowed type corresponds to what the code has actually verified.

Use tags and reusable predicates

typescript
// Prefer discriminated unions over instanceof checks for domain types
type ApiEvent =
  | { type: 'request';  url: string; method: string }
  | { type: 'response'; status: number; body: string }
  | { type: 'error';    message: string; code: number };

function handleEvent(e: ApiEvent): void {
  switch (e.type) {
    case 'request':  console.log(e.method, e.url); break;
    case 'response': console.log(e.status);        break;
    case 'error':    console.error(e.message);     break;
  }
}

// Reusable type predicates
function isNonNull<T>(val: T | null | undefined): val is T {
  return val !== null && val !== undefined;
}
const ids: (string | null)[] = ['a', null, 'b'];
const validIds = ids.filter(isNonNull);   // string[]

// assertNever for exhaustiveness
function assertNever(x: never): never {
  throw new Error('unhandled case: ' + JSON.stringify(x));
}

A tag selects a variant and a reusable predicate names a check.

Validate unknown input at the boundary

typescript
// Use the relevant declarations from the preceding example.
// Narrow unknown at system boundaries
function parseConfig(raw: unknown): { host: string; port: number } {
  if (
    typeof raw !== 'object' || raw === null ||
    !('host' in raw) || typeof (raw as { host: unknown }).host !== 'string' ||
    !('port' in raw) || typeof (raw as { port: unknown }).port !== 'number'
  ) throw new TypeError('invalid config');
  return raw as { host: string; port: number };
}

// satisfies — validate shape without widening literal types
const palette = {
  primary:   '#3b82f6',
  secondary: '#6366f1',
} satisfies Record<string, string>;
palette.primary;   // type is '#3b82f6', not string

// Use 'in' operator for duck-typing object shapes
function isCat(animal: unknown): animal is { meow(): void } {
  return typeof animal === 'object' && animal !== null && 'meow' in animal;
}

Inspect external data before treating it as an application type.

Async & Error Handling

Describe asynchronous results and error paths explicitly. Annotations do not change scheduling or guarantee the shape of caught errors.

Annotate the successful value inside Promise where it clarifies the contract. At a catch boundary, narrow the caught value before reading its message, since JavaScript can throw values other than Error objects.

Model asynchronous success and failure

typescript
// Always annotate async return types explicitly
async function fetchUser(id: string): Promise<User> {
  const res = await fetch('/api/users/' + id);
  if (!res.ok) throw new Error('fetch failed: ' + res.status);
  return res.json() as Promise<User>;
}

// Result<T, E> for expected errors — no-throw control flow
type Ok<T>  = { ok: true;  value: T };
type Err<E> = { ok: false; error: E };
type Result<T, E = Error> = Ok<T> | Err<E>;

async function safeParseUser(id: string): Promise<Result<User>> {
  try {
    const user = await fetchUser(id);
    return { ok: true, value: user };
  } catch (e: unknown) {
    return { ok: false, error: e instanceof Error ? e : new Error(String(e)) };
  }
}

// catch as unknown in strict mode — never assume error shape
async function run(): Promise<void> {
  try {
    await fetchUser('123');
  } catch (e: unknown) {
    if (e instanceof Error) console.error(e.message);
    else console.error('unknown error', e);
  }
}

The return type tells callers how to consume success and expected failures.

Propagate cancellation and stream values

typescript
// Use the relevant declarations from the preceding example.
// Awaited<T> for unwrapping nested promises
type UserResult = Awaited<ReturnType<typeof fetchUser>>;   // User

// AbortSignal in API boundaries
async function fetchWithTimeout(url: string, ms: number): Promise<Response> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), ms);
  try {
    return await fetch(url, { signal: controller.signal });
  } finally {
    clearTimeout(timer);
  }
}

// Async generator for streaming data
async function* streamLines(url: string): AsyncGenerator<string> {
  const res = await fetch(url);
  const reader = res.body!.getReader();
  const decoder = new TextDecoder();
  let buf = '';
  while (true) {
    const { value, done } = await reader.read();
    if (done) break;
    buf += decoder.decode(value, { stream: true });
    const lines = buf.split('\n');
    buf = lines.pop()!;
    for (const line of lines) yield line;
  }
}

Pass a signal to cancellable work. An async generator yields values incrementally.

tsconfig & Tooling

Keep strict checking aligned with the execution environment. Type checking complements runtime tests and external-data validation.

Run the project check locally and in continuous integration with the same configuration. Compiler checks can find type errors before runtime tests exercise behavior.

Set strict project options

typescript
// tsconfig.json — recommended strict baseline for new projects
// {
//   'compilerOptions': {
//     'strict': true,                      // enables all strict checks
//     'noUncheckedIndexedAccess': true,    // arr[i] is T | undefined
//     'exactOptionalPropertyTypes': true,  // no implicit undefined assignment
//     'noImplicitOverride': true,          // require 'override' keyword
//     'moduleResolution': 'bundler',       // modern Vite/esbuild/webpack 5
//     'module': 'ESNext',
//     'target': 'ES2022',
//     'lib': ['ES2022', 'DOM'],
//     'paths': { '@/*': ['./src/*'] },     // import aliases
//     'skipLibCheck': true,
//     'declaration': true,
//     'sourceMap': true
//   }
// }

These flags add checks for optional properties, overrides and indexed reads.

Check and build projects from the command line

typescript
// Run type-check without emitting in CI
// tsc --noEmit

// Profile slow types
// tsc --diagnostics 2>&1 | grep -E 'Instantiation|Check time'

// ESLint typescript plugin — catches common mistakes at lint time
// npm i -D @typescript-eslint/eslint-plugin @typescript-eslint/parser
// .eslintrc: { 'extends': ['plugin:@typescript-eslint/recommended-type-checked'] }

// Project references for monorepos — incremental builds
// tsconfig.json at root:
// {
//   'references': [
//     { 'path': './packages/core' },
//     { 'path': './packages/api' },
//     { 'path': './packages/ui' }
//   ]
// }
// Build all: tsc --build
// Watch:     tsc --build --watch

// noUncheckedIndexedAccess in practice
const items: string[] = ['a', 'b'];
const first: string | undefined = items[0];   // explicit undefined with flag
if (first !== undefined) first.toUpperCase();  // safe after narrow

No-emit checking validates types. Build mode follows configured project references.

Patterns & Architecture

Choose patterns that clarify contracts and responsibilities. Keep type-level machinery proportional to the behavior it protects.

Keep runtime dependencies and type dependencies explicit. Type-only imports clarify boundaries and avoid loading a module just to name one of its types.

Organize modules and declarations

typescript
// Prefer explicit named imports over barrel re-exports for deep trees
// Barrel files are fine for small, stable public APIs
// Avoid: import { everything } from '@/components'  — slows down bundlers
// Prefer: import { Button } from '@/components/Button'

// Declaration merging — augment third-party types without forking
import 'express';
declare module 'express' {
  interface Request {
    currentUser?: { id: string; role: string };
  }
}

// Const enums — avoid with isolatedModules (esbuild / Babel can't inline them)
// Use plain string union or object enum instead:
const Direction = { Up: 'UP', Down: 'DOWN', Left: 'LEFT', Right: 'RIGHT' } as const;
type Direction = typeof Direction[keyof typeof Direction];

Named imports show the dependency directly. Augmentation extends types for existing behavior.

Share implementations and validate data

typescript
// Prefer abstract classes over interfaces when sharing implementation
abstract class BaseRepository<T> {
  abstract findById(id: string): Promise<T | null>;

  async findOrThrow(id: string): Promise<T> {
    const item = await this.findById(id);
    if (!item) throw new Error('not found: ' + id);
    return item;
  }
}

// Runtime validation at boundaries — generate types from schemas
// import { z } from 'zod';
// const UserSchema = z.object({ id: z.string(), name: z.string(), age: z.number() });
// type User = z.infer<typeof UserSchema>;   // type comes from the schema
// const user = UserSchema.parse(req.body);  // validated at runtime

// Never write types first and try to match them with validators later
// Schema -> type  (single source of truth)
// Type   -> schema (duplication — risk of drift)

// Use satisfies for config objects to catch typos without widening
type Route = { path: string; component: string; exact?: boolean };
const routes = [
  { path: '/',       component: 'Home',    exact: true },
  { path: '/about',  component: 'About' },
  { path: '/users',  component: 'Users' },
] satisfies Route[];

An abstract base can share implementation. A schema validates data that arrives at runtime.

Diagram
100%