"Most real values are one-of-several. Unions are how you say that to the type system."
What unions describe
A union type A | B describes a value whose type is one of the listed alternatives. The value is, at any given moment, exactly one of those types — never both, never neither. The compiler tracks which one through control flow.
Unions are the most common way to model real-world data in TypeScript. A status field that could be one of four strings. A response that could be a success or an error. A configuration option that accepts a string OR a function returning a string. All of these are unions.
Operations on union values
You can only access properties or call methods that exist on every member of the union. (string | number).toUpperCase() fails because number doesn't have toUpperCase. To use type-specific operations, you have to narrow first — typeof checks, instanceof, in operators, or custom type guards. The narrowing track covers this in depth.
Common patterns
- Literal-string union:
'idle' | 'loading' | 'done'— the enum-by-convention pattern. - Nullable:
string | nullorstring | undefined— explicitly optional. - Tagged shape union:
{ kind: 'a'; x: number } | { kind: 'b'; y: string }— discriminated unions (next-but-one lesson). - Function-or-value:
string | (() => string)— accept either a literal or a producer.