0Pricing
TypeScript Academy · Lesson

Combining Literals into Unions

Build finite value sets by unioning literal types.

Unions of Literal Types

A union of literals models a value that must be exactly one of several known options. It is the backbone of state machines, enums, and well-typed APIs.

type Status = 'idle' | 'loading' | 'success' | 'error';

let state: Status = 'idle';
state = 'loading';
console.log('State:', state);

Switching on a Literal Union

A switch over a literal union reads cleanly and the compiler knows each case is one of the allowed values. This pairs perfectly with exhaustiveness checks.

type Status = 'idle' | 'loading' | 'done';

function label(s: Status): string {
  switch (s) {
    case 'idle': return 'Waiting';
    case 'loading': return 'Working';
    case 'done': return 'Finished';
  }
}
console.log(label('loading'));

All lessons in this course

  1. String and Numeric Literal Types
  2. Boolean Literals and Literal Inference
  3. const Assertions with as const
  4. Combining Literals into Unions
← Back to TypeScript Academy