There is value in explicitly modeling every meaningful state for a software program in types. This gives your implementation a behavioral model to follow.
For example, in a simplified order flow:
- List the potential states: draft, submitted, invoiced, paid.
- List the required data: a paid order requires a payment date while a draft order does not.
- List transitions and their conditions: marking an invoiced order paid requires payment evidence. Cancellations, partial payments, and refunds need admin approval before changing.
In the world of type-safe coding, this can be referred to as state modeling:
- State space: All potential combinations for a set of variables (including contradictory ones).
- State model: The situations the system permits. The system may require specific data or only allow specific moves. This becomes a behavioral spec before it becomes code.
The goal is to make invalid states unrepresentable through types. This makes it harder for agents to generate code that results in invalid states (leading to less bugs). Though it does not necessarily cover the logic for business rules, access controls, or runtime inputs.
Example — an order that can only be paid after invoicing
A loose model might give an order a status and optional invoiceId and paidAt fields. That permits a contradictory combination: status: "paid" with no payment date. Instead, give each state its own shape.
type Order =
| { status: "draft"; id: string }
| { status: "submitted"; id: string; submittedAt: Date }
| { status: "invoiced"; id: string; invoiceId: string }
| {
status: "paid";
id: string;
invoiceId: string;
paymentId: string;
paidAt: Date;
};
type InvoicedOrder = Extract<Order, { status: "invoiced" }>;
type PaidOrder = Extract<Order, { status: "paid" }>;
// This transition accepts only an invoiced order.
function markPaid(
order: InvoicedOrder,
payment: { id: string; receivedAt: Date },
): PaidOrder {
return {
...order,
status: "paid",
paymentId: payment.id,
paidAt: payment.receivedAt,
};
}
const invoice: InvoicedOrder = {
status: "invoiced",
id: "order-1",
invoiceId: "invoice-1",
};
const payment = { id: "payment-1", receivedAt: new Date() };
const paid = markPaid(invoice, payment);
// These lines intentionally demonstrate compiler errors.
// @ts-expect-error A draft cannot be passed to this transition.
markPaid({ status: "draft", id: "order-2" }, payment);
// @ts-expect-error A paid order must include paymentId and paidAt.
const incomplete: PaidOrder = {
status: "paid", id: "order-3", invoiceId: "invoice-3",
};
In this state model, status is the discriminant and Extract selects one member of the union. The function signature describes the action: if an invoiced order has received payment, mark it paid.
The same model can make UI decisions exhaustive:
function orderLabel(order: Order): string {
switch (order.status) {
case "draft":
return "Draft";
case "submitted":
return `Submitted ${order.submittedAt.toISOString()}`;
case "invoiced":
return `Invoice ${order.invoiceId}`;
case "paid":
return `Paid ${order.paidAt.toISOString()}`;
default: {
const unhandled: never = order;
throw new Error(`Unhandled order: ${unhandled}`);
}
}
}
Add a cancelled variant to Order and the never assignment fails until this function handles it. The compiler points to a missing decision.
This example models one transition and the data needed for it; it is not a complete order ledger. The application must still validate that a payment exists, belongs to this invoice, and covers the amount due. It must also authorize the action and persist it atomically without recording a retry twice. TypeScript checks the shapes in checked code. It does not validate incoming JSON or prevent another caller from constructing a PaidOrder directly.