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
- String and Numeric Literal Types
- Boolean Literals and Literal Inference
- const Assertions with as const
- Combining Literals into Unions