TypeScript · Lesson 3

Union Types

Unions vs intersections, discriminated unions, exhaustive matching with never, state modelling, reducers, Extract/Exclude and branded types.

6 min read

In short

  • Unions describe alternatives; narrow before use
  • A literal tag like kind makes a discriminated union
  • Model states as members so bad combinations can't exist
  • assertNever turns a missed case into a compile error
  • Brands stop structurally equal IDs from mixing

If generics are how TypeScript describes relationships, unions are how it describes alternatives. Most domain modelling in a well-typed codebase is done with discriminated unions, and most runtime bugs they prevent are the "this field can't be set in that state" kind.

Unions and intersections as sets

Think of a type as the set of values it allows.

  • A | B (union): values that are an A or a B. You may only use what all members have in common until you narrow.
  • A & B (intersection): values that are both. For object types that means all properties of both.
▶ Try
type Id = string | number;
function show(id: Id) {
  id.toString();      // OK: both have toString
  // id.toUpperCase(); // error: number has no toUpperCase
}

type Timestamped = { createdAt: Date };
type Named = { name: string };
type Entity = Named & Timestamped;   // { name: string; createdAt: Date }

type Impossible = string & number;   // never: no value is both

The counter-intuitive part: a union of object types has fewer accessible properties, and an intersection has more, which is the opposite of what | and & suggest about the keys. keyof (A | B) is the keys common to both; keyof (A & B) is all keys.

Discriminated unions

A discriminated (tagged) union is a union of object types that share a literal-typed property, the discriminant:

▶ Try
type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'rect'; width: number; height: number }
  | { kind: 'triangle'; base: number; height: number };

function area(s: Shape): number {
  switch (s.kind) {
    case 'circle':   return Math.PI * s.radius ** 2;   // s narrowed to the circle member
    case 'rect':     return s.width * s.height;
    case 'triangle': return (s.base * s.height) / 2;
  }
}

Checking s.kind narrows s to the matching member(s). This works with switch, if, ===/!==, early returns and destructuring (const { kind } = s; if (kind === 'circle') s.radius). The discriminant can be any literal type: strings (most readable), numbers, booleans or undefined.

Exhaustiveness with never

After every case is handled, the remaining type is never. Use that to make the compiler tell you when a new member is added and not handled:

▶ Try
function assertNever(value: never, message = 'Unexpected value'): never {
  throw new Error(`${message}: ${JSON.stringify(value)}`);
}

function label(s: Shape): string {
  switch (s.kind) {
    case 'circle': return 'Circle';
    case 'rect': return 'Rectangle';
    case 'triangle': return 'Triangle';
    default: return assertNever(s); // compile error here if a case is missing
  }
}

Without the default, strict mode still catches a missing case when the function has a return type annotation ("Function lacks ending return statement and return type does not include 'undefined'", TS2366), but not in void functions or reducers that fall through to return state. assertNever also protects you at runtime when data from outside doesn't match the type. An alternative that needs no helper: const _exhaustive: never = s;. The @typescript-eslint/switch-exhaustiveness-check lint rule automates the same idea.

Making illegal states unrepresentable

The classic bad model:

▶ Try
interface RequestState<T> {
  loading: boolean;
  error?: string;
  data?: T;
}

This permits loading: true with data and error, which is 8 combinations of which maybe 4 make sense. Every consumer has to guess. Model it as a union instead:

▶ Try
type RequestState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: string };

Now data exists only in the success state, and the compiler forces consumers to check status before touching it. The same idea applies to payment flows, form wizards, websocket connections and feature rollout states.

Reducers and action unions

Redux, useReducer, Elm, and event-sourced backends all follow the same shape: a pure function (state, action) => state where actions are a discriminated union:

▶ Try
type CounterAction =
  | { type: 'increment'; by: number }
  | { type: 'reset' };

function reducer(state: number, action: CounterAction): number {
  switch (action.type) {
    case 'increment': return state + action.by;
    case 'reset': return 0;
    default: return assertNever(action);
  }
}

type ActionType = CounterAction['type'];                          // 'increment' | 'reset'
type IncrementAction = Extract<CounterAction, { type: 'increment' }>;

Indexing a union with its discriminant (U['type']) gives the union of tags, which is useful for building handler maps and action-creator types.

Extract and Exclude

▶ Try
type Exclude<T, U> = T extends U ? never : T;   // remove members assignable to U
type Extract<T, U> = T extends U ? T : never;   // keep members assignable to U

type Primitive = string | number | boolean | null;
type NonNull = Exclude<Primitive, null>;                        // string | number | boolean
type Circles = Extract<Shape, { kind: 'circle' }>;              // the circle member
type WithHeight = Extract<Shape, { height: number }>;           // rect | triangle

They operate member by member (that's distributive conditional types, covered later), which makes them ideal for filtering discriminated unions.

Branded (nominal) types

TypeScript is structural: a UserId that is just string will happily accept an OrderId or an email. Branding adds a phantom property that exists only in the type system:

▶ Try
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };

type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;

function toUserId(raw: string): UserId {
  if (!raw.startsWith('usr_')) throw new Error('Invalid user id');
  return raw as UserId;   // the only cast, inside a validating constructor
}

function loadUser(id: UserId) { /* ... */ }
loadUser(toUserId('usr_1'));        // OK
// loadUser('usr_1');               // error: string is not a UserId
// loadUser(orderId);               // error: OrderId is not a UserId

A UserId is still a string (you can pass it to string APIs), but not vice versa. Brands are perfect for IDs, validated values (Email, NonEmptyString), and units (Cents, Milliseconds) where mixing them up is a real bug.

Gotchas

  • Excess property checks catch { status: 'loading', data: x } only on fresh object literals. A variable with extra properties can still be assigned.
  • Destructuring too early: const { data } = state before checking status doesn't even compile, because data isn't on every member. Check the tag first. When every member has the same payload field, you can also destructure the tag together with the payload into consts (const { type, payload } = action, TS 4.6+), which keeps them linked.
  • Non-literal discriminants don't discriminate. kind: string on one member ruins narrowing for the whole union.
  • Optional-property unions like { a?: string; b?: number } are not a substitute for a real union: nothing says "exactly one".

In real codebases

Side note

Discriminated unions are how you type API responses ({ ok: true; data } | { ok: false; error }), Redux/NgRx actions, WebSocket messages, domain events, and UI state machines. Combined with assertNever, they turn "we added a new payment method and forgot the receipt template" from a production bug into a compile error.

Practise this lesson

In the app: a short video, 7 exercises checked by real tests and a 11-question concept check. Free with a GitHub account.

Open in the app