Union Types
A union type describes a value that is one of several types, written A | B. Until you narrow it, you may only use the members that every branch of the union has in common.
Detailed Explanation
Real programs are full of values that are one thing or another. An ID arrives as a string from a URL and a number from the database. A fetch either returns data or fails. A form field is filled in or empty. Before unions, the usual workaround in typed languages was to widen everything to a common base type and cast on the way out, which throws away exactly the information you needed.
A union says "one of these, I do not yet know which." Think of a type as the set of values it allows: string | number is the set of all strings combined with the set of all numbers.
Here is the part that confuses people. Combining two types with | gives you a bigger set of values but a smaller set of guaranteed members. If a value might be a string or a number, you cannot call .toUpperCase() on it, because numbers do not have that method. TypeScript only lets you touch what is safe on every branch.
To use the branch-specific parts, you narrow. Narrowing is the compiler following ordinary JavaScript checks and shrinking the type inside a block:
typeof value === "string"for primitivesArray.isArray(value)for arraysvalue instanceof Responsefor class instances"error" in payloadfor object shapesvalue === null,if (value)for nullish checks- comparing a shared literal property, which is the discriminated union pattern
All of these are real runtime checks. Types are erased, so narrowing works by the compiler reading code that genuinely executes. There is no magic reflection underneath.
Unions are how strictNullChecks models absence: with that flag on, a value that might be missing is string | undefined, and the compiler makes you handle the undefined case before you use it. That single change catches more bugs than any other feature in the language.
A few behaviours worth knowing early. Unions are flattened and deduplicated, so string | (string | number) is just string | number. never disappears from a union entirely, because the empty set adds nothing. any swallows the union, because everything is assignable to any. And keyof (A | B) is the intersection of their keys, not the union — only keys present on both are safe to read.
The cost is mostly cognitive and structural. A union of many object shapes forces a narrowing step at every use site, which is usually the correct pressure but can be tedious. Very large unions slow the compiler down, because assignability has to be checked branch by branch. And a union with no discriminating property is painful to narrow; adding a literal kind field to each branch is nearly always worth it.
Code Examples
1. Only common members are available until you narrow.
// 1. Only common members are available until you narrow.
type Id = string | number;
function describe(id: Id): string {
// id.toUpperCase();
// Error: Property 'toUpperCase' does not exist on type 'number'.
if (typeof id === "string") {
return id.toUpperCase(); // narrowed to string inside this block
}
return id.toFixed(0); // narrowed to number in the else path
}
console.log(describe("abc")); // "ABC"
console.log(describe(42.7)); // "43"2. Modelling an API call that either succeeds or fails.
// 2. Modelling an API call that either succeeds or fails.
type PaymentResult =
| { status: "succeeded"; chargeId: string; cents: number }
| { status: "failed"; reason: string }
| { status: "pending" };
function summarize(result: PaymentResult): string {
switch (result.status) { // the shared literal property narrows each case
case "succeeded":
return `Charged ${result.cents} (${result.chargeId})`;
case "failed":
return `Declined: ${result.reason}`;
case "pending":
return "Awaiting bank confirmation";
}
}
// Accessing result.reason outside the "failed" branch is a compile error,
// which is the entire point of modelling the states as a union.3. Unions under strictNullChecks, and the keyof surprise.
// 3. Unions under strictNullChecks, and the keyof surprise.
function firstName(users: string[]): string | undefined {
return users[0]; // may be undefined at runtime
}
const name = firstName([]);
// name.trim();
// Error: 'name' is possibly 'undefined'.
if (name !== undefined) name.trim(); // narrowed, safe
type Cat = { name: string; purrs: boolean };
type Dog = { name: string; barks: boolean };
type Pet = Cat | Dog;
type PetKeys = keyof Pet; // "name" only — the keys common to both, not all threeCommon Gotchas
`string[] | number[]` is not `(string | number)[]`
the first is "an array of one kind or the other" and rejects `push` of either type, because the compiler cannot pick a signature. The second is "an array whose elements may be either" and accepts both.
Narrowing is lost across a function boundary
the compiler resets what it knows when you pass a narrowed value into a callback or reassign it later. Extract the narrowed value into a `const` and use that.
`never` vanishes and `any` takes over
`string | never` is `string`, and `string | any` is `any`. A union that unexpectedly collapsed to `any` usually has an untyped value hiding in one branch.
Unions without a discriminant are hard to use
narrowing `{ a: string } | { b: string }` requires `in` checks scattered everywhere. Add a literal tag property to each branch and the whole thing becomes a `switch`.