Order Lifecycle: Illegal States Unrepresentable

Lesson 4 of the DDD course · Lifecycle as a discriminated union, exhaustiveness, typed transitions · ~30 minutes

1 · Value objects 2 · Entities & identity 3 · Aggregates 4 · Lifecycle state machines 5 · Domain events 6 · Bounded contexts 7 · Context mapping 8 · Functional core 9 · Capstone
Why this matters for your mission The classic startup bug: an order marked shipped that was never paid, because some code path set fields directly. Today the lifecycle becomes the type system's job — the compiler refuses to ship a draft, in every code path, forever.

This is the lesson where functional TypeScript stops imitating OOP DDD and starts beating it. What classes-with-inheritance do awkwardly, discriminated unions do natively.

1 · The lie of status: string

Here's the model everyone writes first:

interface Order {
  id: OrderId;
  status: string;            // "draft" | "placed" | "shipped" … in someone's head
  paymentId?: PaymentId;     // present when placed… usually
  shipment?: Shipment;       // present when shipped… we hope
}

Count what this type permits: status: "draft" with a shipment. status: "shipped" with no paymentId. Every optional field doubles the state space, and only a handful of combinations are legal. So every consumer writes defensive checks — “is payment there? is it shipped? am I sure?” — forever, for states that should not exist.

The principle Make illegal states unrepresentable. If a combination can't happen in the business, model your types so it can't happen in the code. Then the compiler — not your discipline — deletes the defensive checks.[Wlaschin]

2 · One type per stage

interface DraftOrder {
  readonly kind: "draft";                 // the discriminant
  readonly id: OrderId;
  readonly customerId: CustomerId;
  readonly lines: readonly OrderLine[];
  readonly total: Cents;
}

interface PlacedOrder {
  readonly kind: "placed";
  readonly id: OrderId;
  readonly customerId: CustomerId;
  readonly lines: readonly OrderLine[];
  readonly total: Cents;
  readonly paymentId: PaymentId;          // only a placed order was paid
}

interface ShippedOrder {
  readonly kind: "placed" | "shipped";    // hmm — see below
  readonly shipment: Shipment;            // only a shipped order has one
}

type Order = DraftOrder | PlacedOrder | ShippedOrder;

Each stage carries only the data valid at that stage. A DraftOrder has no paymentId because drafts aren't paid. There is no such value as “a shipped order without a shipment” — the type won't construct one. The impossible states aren't checked at runtime; they're inexpressible.[Wlaschin]

3 · Transitions are the only doors

function ship(o: PlacedOrder, carrier: Carrier): Result<ShippedOrder, ShipError>

ship(draftOrder, carrier);   // ☠ compile error: DraftOrder is not PlacedOrder

The parameter type is the state machine. ship can't be called on a draft — not “will throw if you do”, but the program doesn't compile. Two layers of protection now cooperate:

And narrowing reads like the business: switch (order.kind) — in the "placed" branch, order.paymentId is simply there, no optional gymnastics:

function trackingUrl(o: Order): string | null {
  switch (o.kind) {
    case "draft":   return null;
    case "placed":  return null;
    case "shipped": return o.shipment.trackingUrl;
  }
}

4 · Exhaustiveness: the compiler as a checklist

Add a "refunded" stage next quarter. Watch what happens:

function assertNever(x: never): never {
  throw new Error("unhandled stage: " + JSON.stringify(x));
}

function label(o: Order): string {
  switch (o.kind) {
    case "draft":  return "Cart";
    case "placed": return "Confirmed";
    default:      return assertNever(o);  // ☠ won't compile until handled
  }
}

assertNever turns the union into a work list: every place that must learn about the new stage fails the build until updated. String statuses give you the opposite — a switch with a silent default and a hope.

Gotchas (1) The discriminant field must use literal types (kind: "draft"), or narrowing dies. (2) Don't share one mega-interface with optional fields “for convenience” — that re-opens the illegal combinations. (3) Keep stage data minimal: if Shipment data is huge, ship a ShipmentId and load it in the shell (Lesson 8).

5 · Practice: the place() transition

6 · Retrieval check

7 · Where this goes next

Placing an order has consequences — emails, warehouse feeds, analytics. Next lesson: domain events, the pattern that lets pure transitions announce facts without knowing who listens.

Your teacher is the agent If the never trick or narrowing behavior surprises you, ask — I can walk through exactly what the compiler proves, line by line. Understanding why it's safe is what makes you able to design new unions on your own product.
Primary source for this lesson Read Wlaschin's “Making illegal states unrepresentable” (~10 min) — this lesson is its TypeScript translation. For depth on modeling workflows as data: *Domain Modeling Made Functional*, part 2.
← Lesson 3: Aggregates Patterns cheat sheet →