Skip to content
jshacks.dev
Patterns

Design by Contract in TypeScript

Design by contract states what a function requires, guarantees and always keeps true. Write preconditions, postconditions and invariants with TypeScript.

9 min read
Summarize in AI
Flat illustration of a service container binding interfaces to classes, with the JavaScript and npm logos.

Design by contract is a way of writing code where each function states, in code, what it requires from its callers, what it promises in return and what must always stay true about the objects it works on. The terms come from Bertrand Meyer's Eiffel language: preconditions, postconditions and invariants. TypeScript has no built-in contract syntax, but its assertion signatures and plain functions give you most of the benefit. This post builds a small contract toolkit on TypeScript 5.9 and Node.js 24, applies it to an account and a sorting helper, explains who is to blame when a contract breaks, and covers how contracts relate to types, validation and tests.

Three kinds of promise

A precondition is what must be true when a function is called. It is the caller's responsibility: if a precondition fails, the bug is in the code that made the call. A postcondition is what the function guarantees when it returns normally. It is the function's responsibility: if it fails, the bug is inside the function. An invariant is a condition that holds for an object whenever no method is running, before and after every public call.

The blame assignment is the useful part. Without contracts, a wrong result surfaces somewhere downstream and you hunt backward through the code. With contracts, the failing check points at the side that broke the agreement, and the message says which kind of promise it was.

A small toolkit with assertion signatures

TypeScript's asserts condition return type tells the compiler that after the call returns, the condition holds, so it narrows types in the code that follows.

contract.tsTypeScript
export function requires(condition: boolean, message: string): asserts condition {
  if (!condition) throw new Error(`precondition failed: ${message}`);
}

export function ensures(condition: boolean, message: string): asserts condition {
  if (!condition) throw new Error(`postcondition failed: ${message}`);
}

export function invariant(condition: boolean, message: string): asserts condition {
  if (!condition) throw new Error(`invariant violated: ${message}`);
}

Three small functions with distinct names make the failure message say which kind of promise broke. That is worth the separate names: a log line reading "precondition failed" sends you to the caller, and "postcondition failed" sends you into the function. TypeScript requires an assertion function to be called through a name with an explicit type annotation, which imported function declarations satisfy.

Preconditions on a method

Take an account that must never go negative.

account.tsTypeScript
import { requires, ensures, invariant } from "./contract.ts";

export class Account {
  #balance: number;

  constructor(opening: number) {
    requires(Number.isFinite(opening) && opening >= 0, "opening balance must be a non-negative number");
    this.#balance = opening;
    this.#checkInvariant();
  }

  get balance(): number {
    return this.#balance;
  }

  withdraw(amount: number): number {
    requires(Number.isFinite(amount) && amount > 0, "amount must be a positive number");
    requires(amount <= this.#balance, "amount must not exceed the balance");

    const before = this.#balance;
    this.#balance -= amount;

    ensures(this.#balance === before - amount, "balance decreased by exactly the amount");
    this.#checkInvariant();
    return this.#balance;
  }

  #checkInvariant(): void {
    invariant(this.#balance >= 0, "balance is never negative");
  }
}

const account = new Account(100);
console.log(account.withdraw(30));

for (const amount of [500, -5]) {
  try {
    account.withdraw(amount);
  } catch (err) {
    console.log((err as Error).message);
  }
}
console.log(account.balance);
Text
70
precondition failed: amount must not exceed the balance
precondition failed: amount must be a positive number
70

The two failed calls left the balance at 70, because preconditions run before any state changes. That ordering is a rule worth keeping: check everything the function needs first, then change things. A precondition that fires halfway through a mutation leaves an object in an unknown state, and the invariant check afterward would have to catch it.

Postconditions catch the function's own bugs

A postcondition checks the result against the promise. They are most valuable for code with some complexity, where a mistake is plausible.

top-scores.tsTypeScript
import { requires, ensures } from "./contract.ts";

export function topScores(scores: number[], n: number): number[] {
  requires(Number.isInteger(n) && n >= 0, "n must be a non-negative integer");

  const result = [...scores].sort((a, b) => b - a).slice(0, n);

  ensures(result.length <= n, "at most n results");
  ensures(
    result.every((value, i) => i === 0 || result[i - 1] >= value),
    "results are sorted descending",
  );
  return result;
}

console.log(topScores([5, 3, 9, 1], 2));
console.log(topScores([5, 3], 5));

try {
  topScores([5, 3], -1);
} catch (err) {
  console.log((err as Error).message);
}
Text
[ 9, 5 ]
[ 5, 3 ]
precondition failed: n must be a non-negative integer

The function copies the array before sorting, because sort mutates in place, and the postconditions state what a caller can rely on: no more than n items, in descending order. If someone later "optimizes" the function and breaks the ordering, the second ensures fails at the call and names the broken promise. For this particular function the postconditions restate the implementation, so they add little, and that is an honest limit: a postcondition is most useful when it checks a property that is easier to verify than to compute, such as "the result is sorted" for an algorithm that sorts in a complicated way.

Invariants hold between calls

An invariant describes a state that must be true whenever the object is observable from outside. The account's invariant is that the balance is never negative. A stronger example is a class that keeps two fields in step.

range.tsTypeScript
import { requires, invariant } from "./contract.ts";

export class Range {
  #start: number;
  #end: number;

  constructor(start: number, end: number) {
    requires(start <= end, "start must not be after end");
    this.#start = start;
    this.#end = end;
  }

  extendTo(end: number): void {
    requires(end >= this.#end, "a range can only grow");
    this.#end = end;
    invariant(this.#start <= this.#end, "start never exceeds end");
  }

  get length(): number {
    return this.#end - this.#start;
  }
}

const range = new Range(10, 20);
range.extendTo(35);
console.log(range.length);

try {
  range.extendTo(5);
} catch (err) {
  console.log((err as Error).message);
}
try {
  new Range(8, 3);
} catch (err) {
  console.log((err as Error).message);
}
Text
25
precondition failed: a range can only grow
precondition failed: start must not be after end

Private fields do the heavy lifting here. Because nothing outside the class can write #start or #end, the invariant only has to be checked inside the class's own methods, which makes it feasible to prove by reading a small amount of code. If the fields were public, any caller could break the invariant and every check would have to run everywhere.

Contracts and types are partners

TypeScript types express shape: this is a number, that is an array of strings. Contracts express relationships and values: this number is positive, that index is inside this array, the first argument is not larger than the second. The two cover different ground, and the best code uses both. When a contract is simple and reused, push it into the type.

branded.tsTypeScript
declare const brand: unique symbol;
export type Positive = number & { readonly [brand]: "Positive" };

export function toPositive(n: number): Positive {
  if (!Number.isFinite(n) || n <= 0) throw new RangeError(`not a positive number: ${n}`);
  return n as Positive;
}

export function area(width: Positive, height: Positive): number {
  return width * height;
}

console.log(area(toPositive(4), toPositive(2.5)));
// area(4, 2.5);   // error: 'number' is not assignable to 'Positive'
Text
10

A branded type moves the precondition to the place where the value is created, and the compiler then guarantees it everywhere else, so area needs no check of its own. This is the same idea as parsing instead of validating: convert untrusted data into a type that proves its own validity once, and let every later function rely on the proof. Use branded types for conditions that recur, such as positive numbers, non-empty strings and validated email addresses, and keep requires for conditions that involve several arguments or the object's state.

Who catches a contract error

A failed contract is a bug in the program, not a condition to recover from. Do not wrap a precondition failure in a try and carry on, since that turns the bug into silent misbehavior. Let it propagate to a top-level handler that logs it with the stack and fails the request or the process, depending on the application. This is the line between contracts and input validation. Data from users, files and other systems is expected to be wrong sometimes, and that is handled with validation that produces an ordinary error response. A contract guards against mistakes by programmers, in calls between your own functions, and a failure there should be loud.

A practical split is to validate at the boundary, producing friendly errors, and use contracts inside, trusting that the boundary did its job. If a contract fails on data that came from outside, the boundary check is missing, which is a useful finding in itself.

Contracts and inheritance

If a class has subclasses, the contract has to survive them. The rule from the Liskov substitution principle is that a subclass may accept more than its parent, by weakening preconditions, and may promise more, by strengthening postconditions, but never the reverse. A subclass of Account that required withdrawals to be multiples of ten would strengthen a precondition, and code written against Account would break when handed the subclass. Writing the contract down makes this kind of violation visible in review, and a shared test suite run against every subclass checks it.

Should checks stay on in production

Contracts cost a little time per call. Eiffel made them switchable, and the usual approaches here are to keep cheap checks always on and run expensive ones, such as an invariant that scans a large collection, only in development and tests. Guard those with an environment flag and name them accordingly, so nobody is surprised when behavior differs. Keep preconditions on in production for anything that protects data, such as a withdrawal limit. A failed check that stops a bad write is cheaper than the cleanup afterward.

Testing contracts

Each precondition is a behavior to test: calling with bad input should fail with the named message, and should leave state unchanged. Postconditions and invariants are tested indirectly, by exercising the code with varied inputs and relying on the checks to fail if anything is wrong.

contract.test.tsTypeScript
import assert from "node:assert/strict";
import { test } from "node:test";
import { Account } from "./account.ts";

test("a rejected withdrawal leaves the balance unchanged", () => {
  const account = new Account(50);
  assert.throws(() => account.withdraw(80), /precondition failed: amount must not exceed the balance/);
  assert.equal(account.balance, 50);
});

test("an invalid opening balance is rejected", () => {
  assert.throws(() => new Account(-1), /precondition failed/);
});
Text
✔ a rejected withdrawal leaves the balance unchanged (0.9ms)
✔ an invalid opening balance is rejected (0.3ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

The contracts make property-style testing cheap. Feed a function many generated inputs and let its own postconditions act as the oracle: any input that fails a postcondition is a counterexample.

When not to use it

For tiny internal helpers, a contract can be longer than the function. For code at the boundary, validation with useful messages for users is the right tool, not an assertion. And contracts do not replace tests: they check the cases that run, and tests choose the cases. Use contracts where a function has non-obvious rules, where objects must keep an invariant and where failures should point at the culprit.

Also inTypeScript
Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.