foundation

Union, intersection, and literal types

Model alternatives, composition, exact values, finite states, and string or numeric domains.

Union types model alternatives: a value must be valid for at least one member. Intersection types combine requirements from multiple types. Literal types constrain values to exact strings, numbers, booleans, or enums.

					type Status = 'idle' | 'loading' | 'done';
type Admin = User & { role: 'admin' };
				

Consumers need narrowing before branch-specific access. Intersections of incompatible properties can collapse to `never`. Wide `string` loses useful literal information unless you preserve it with `as const` or `satisfies`.

On interviews: explain finite domains for statuses and commands, and why unions encode state machines more safely than many optional fields.

Common pitfalls: mixing similar APIs and forgetting edge cases during live coding.

The trade-off is often clarity versus safety or expressiveness versus maintainability. Checklist:

  • Use unions for alternatives.
  • Use intersections for combined contracts.
  • Preserve literals intentionally.
  • Narrow before access.