typescript 38 lines · 8 steps

A type-safe order state machine in TypeScript

A const object plus a derived union type model order statuses and enforce legal transitions at compile and runtime.

Explained by highlit
1export const OrderStatus = {
2 Pending: 'pending',
3 Paid: 'paid',
4 Shipped: 'shipped',
5 Delivered: 'delivered',
6 Cancelled: 'cancelled',
7} as const;
8 
9export type OrderStatus = (typeof OrderStatus)[keyof typeof OrderStatus];
10 
11const TERMINAL: ReadonlySet<OrderStatus> = new Set([
12 OrderStatus.Delivered,
13 OrderStatus.Cancelled,
14]);
15 
16const TRANSITIONS: Record<OrderStatus, readonly OrderStatus[]> = {
17 [OrderStatus.Pending]: [OrderStatus.Paid, OrderStatus.Cancelled],
18 [OrderStatus.Paid]: [OrderStatus.Shipped, OrderStatus.Cancelled],
19 [OrderStatus.Shipped]: [OrderStatus.Delivered],
20 [OrderStatus.Delivered]: [],
21 [OrderStatus.Cancelled]: [],
22};
23 
24export function isOrderStatus(value: unknown): value is OrderStatus {
25 return typeof value === 'string' && (Object.values(OrderStatus) as string[]).includes(value);
26}
27 
28export function isTerminal(status: OrderStatus): boolean {
29 return TERMINAL.has(status);
30}
31 
32export function canTransition(from: OrderStatus, to: OrderStatus): boolean {
33 return TRANSITIONS[from].includes(to);
34}
35 
36export function nextStatuses(from: OrderStatus): readonly OrderStatus[] {
37 return TRANSITIONS[from];
38}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1A const object with a derived union type gives you enum-like values plus real string literals for free.
  2. 2Encoding legal transitions in a typed Record makes the state machine's rules the single source of truth.
  3. 3A type guard bridges untrusted input into the typed world so the rest of the code can trust the status.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A type-safe order state machine in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code