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

typescript
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';

Wiring validation and Swagger docs in NestJS

validation openapi decorators
Intermediate 8 steps
typescript
import { Component, Input } from '@angular/core';
 
interface Order {
  id: string;

How Angular ICU plurals localize an order summary

i18n pluralization standalone-component
Intermediate 8 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, catchError, concatMap, finalize } from 'rxjs';
import { DataSource, QueryRunner } from 'typeorm';
 

Wrapping requests in a transaction with NestJS

interceptors transactions rxjs
Advanced 7 steps
javascript
import { useReducer, useEffect } from "react";
 
const initialState = { status: "idle", data: null, error: null };
 

Building a data-fetching hook in React

custom-hooks usereducer data-fetching
Intermediate 9 steps
typescript
type CsvColumn<T> = {
  header: string;
  value: (row: T) => string | number | boolean | null | undefined;
};

Building a type-safe CSV writer in TypeScript

generics serialization escaping
Intermediate 7 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js';
 
export interface NormalizedPhone {
  e164: string;

Normalizing phone numbers to E.164 in TypeScript

validation normalization error-handling
Intermediate 7 steps

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