Patterns Cheat Sheet

Domain-Driven Design, functional TypeScript · one page per print · pattern → when to reach for it → the skeleton

The seven patterns of this course, compressed. Each row: what it is, when it earns its place, the smallest working TypeScript, and where it was taught. Glossary: glossary.html.

1 · Value object — Lesson 1

A concept with rules and no identity. Immutable; equal by value. Reach for it whenever the business says “a valid X”.

type Email = string & { readonly __brand: "Email" };

function parseEmail(raw: string): Result<Email, string> {
  const email = raw.trim();
  const [local, domain] = email.split("@");
  if (!local || !domain || email.split("@").length !== 2)
    return { ok: false, error: "invalid email" };
  return { ok: true, value: email as Email };
}

Sources: Wlaschin, Designing with types · King, Parse, don't validate

2 · Entity — Lesson 2

A thing with identity that persists through change. Reach for it when “same one again?” matters more than “same values?”.

type CustomerId = string & { readonly __brand: "CustomerId" };

interface Customer {
  readonly id: CustomerId;      // identity: stable across versions
  readonly email: Email;        // state: may change over time
}

const sameCustomer = (a: Customer, b: Customer) => a.id === b.id;

// change = new value, same identity
function changeEmail(c: Customer, raw: string): Result<Customer, string> {
  const r = parseEmail(raw);
  return r.ok ? { ok: true, value: { ...c, email: r.value } } : r;
}

Source: Evans, DDD (entity definition)

3 · Aggregate — Lesson 3

A cluster + root + one consistency boundary. All mutation goes through pure transition functions that enforce invariants and return Result. Other aggregates are referenced by id.

interface Order {
  readonly id: OrderId;
  readonly customerId: CustomerId;  // reference by identity, not object
  readonly status: OrderStatus;
  readonly lines: readonly OrderLine[];
  readonly total: Cents;
}

export function addLine(order: Order, line: OrderLine): Result<Order, OrderError> {
  if (order.status !== "draft") return err("order not editable");
  // …invariants: qty, duplicates, recompute total…
}

Sources: Fowler, DDD Aggregate · Khononov, Learning DDD ch. 10

4 · Lifecycle state machine — Lesson 4

Model stages as a discriminated union; each variant carries only the data valid at that stage. Transitions between stages are the only way to change kind.

type Order =
  | { readonly kind: "draft";  … }
  | { readonly kind: "placed"; …; readonly paymentId: PaymentId }
  | { readonly kind: "shipped"; …; readonly shipment: Shipment };

function ship(o: PlacedOrder): Result<ShippedOrder, ShipError>
// ship(draft) is a compile error — the stage IS the type.

function assertNever(x: never): never { throw new Error("unhandled"); }
// switch exhaustiveness: add a stage ⇒ compiler lists every site.

Source: Wlaschin, Making illegal states unrepresentable

5 · Domain event — Lesson 5

An immutable fact, named in past tense, produced only after success. Transitions return { state, events }; the shell dispatches to handlers.

type OrderEvent =
  | { readonly type: "OrderPlaced";  readonly orderId: OrderId; readonly total: Cents }
  | { readonly type: "OrderShipped"; readonly orderId: OrderId; readonly shipment: Shipment };

// transition output:
{ ok: true, value: { placed, events: [{ type: "OrderPlaced", … }] } }

Sources: Evans, DDD · Khononov, Learning DDD ch. 6

6 · Bounded context + anti-corruption layer — Lessons 6–7

One model per context; same words mean different things across boundaries. Foreign models are translated once, at the edge, by an adapter — never let vendor types leak inward.

// src/shell/bigpay-acl.ts — the ONLY file that knows BigPay's shape
interface BigPayWebhook { event: string; amount: string; currency: string; reference: string }

export function toPaymentReceived(w: BigPayWebhook): Result<PaymentCaptured, AclError> {
  // "payment.succeeded" → "captured"; "1250" → 1250; unknown → typed error
}

Sources: Evans, DDD (context map) · Khononov ch. 9

7 · Functional repository (imperative shell) — Lesson 8

The database is just another untrusted boundary: parse rows into aggregates on load, serialize on save. The core stays synchronous and pure; the shell owns all I/O.

// src/shell/order-repo.ts
export async function loadOrder(id: OrderId): Promise<Result<Order, RepoError>> {
  const row = await db.query("…", [id]);
  return row ? rowToOrder(row) : err("order not found");   // parse, don't trust
}

export function orderToRow(o: Order): OrderRow { /* serialize */ }

Sources: Bernhardt, Boundaries · King, Parse, don't validate

The shared vocabulary these run on

type Result<T, E> =
  | { readonly ok: true;  readonly value: T }
  | { readonly ok: false; readonly error: E };

const err = <E>(error: E) => ({ ok: false as const, error });
Glossary → Capstone walkthrough →