TypeScript Reference ยท Literal and Object Types
TypeScript union types
Reference for TypeScript union types: the | operator, which members you can access, narrowing, unions of literals, distribution and common mistakes.
A union type describes a value that can be one of several types. You write it with the | operator: string | number means "either a string or a number". Unions are how TypeScript models "this or that" data: optional values (T | undefined), results that can fail, or a fixed set of string literals.
You may only use operations that are valid for every member of the union. To use something specific to one member, you first narrow the union with a check such as typeof, in, instanceof, equality, or a discriminant property.
let id: string | number = "A-17"; id = 42;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type U = A | B | C; type Optional = string | undefined; type Leading = | "a" | "b"; // a leading | is allowed and handy for multi-line unions
| Concept | Description |
|---|---|
| Members | The types combined with |. Duplicates and subtypes are simplified where possible. |
| Allowed operations | Properties and methods present in every member. |
never |
The empty union; T | never is just T. |
any / unknown |
any | T collapses to any, and unknown | T collapses to unknown. |
Edge cases: a union of object types lets you read only the properties shared by all members. Assigning to a union variable requires the value to be assignable to at least one member. For writing through a union of property types, the target must satisfy all members (see intersections).
Usage notes
- Distribution: in a conditional type, a naked type parameter distributes over a union (
T extends U ? X : Yis applied per member).keyof (A | B)gives only the keys common to both. - Literal unions replace many enums:
"north" | "east"is erased at runtime, needs no import and works withas constarrays (type D = (typeof dirs)[number]). - Optionals: with
strictNullChecks,stringdoes not includenullorundefined; add them explicitly with a union. - Common mistake: expecting
string | numberto allow.toFixed(); it does not until narrowed. - Discriminated unions add a shared literal field to make narrowing trivial; see Discriminated unions.
- Union versus overloads: a union parameter loses the link between input and output type; use overloads or generics when the return type depends on the argument.
- Size: very large unions (thousands of members) slow type-checking.