A | B Union Types
Last updated: 2026-10-22
A | B Union Types
A union A | B means "the value is A or B". You must narrow it first (typeof, in, ...) so the compiler knows which variant it faces.
| Group | Type Composition |
|---|---|
| Kind | Type |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
type Id = string | number;
let id: Id = "u1";
id = 42; // both are fine
if (typeof id === "number") {
id.toFixed(0); // member access requires narrowing
}
⚙️ Parameters
| A | B | Members separated by |, any count; duplicates merge automatically |
|---|
Returns:None — union types are type-level only and disappear after compilation.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
ABC 3.14
(Runtime output after transpilation; calling value.toUpperCase() without narrowing first is a compile error)
💡 Notes
ℹ️ Info An unnarrowed union only exposes members shared by every variant — the compiler cannot know which one it is.
💡 Tip Choose narrowing by case: typeof (primitives), in (property presence), instanceof (class instances), literal equality (discriminated unions).
⚠️ Note Too many union members means narrowing everywhere; if branches share a tag field, switch to a discriminated union.
🏷️ Related Type Composition
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Why must I narrow before calling methods?
A Calling toUpperCase on string | number would crash if the runtime value were a number. Narrowing is how you prove "it is a string".
Q Union vs any?
A A union enumerates the allowed possibilities and rejects anything else; any permits everything and checks nothing. Unions are bounded choice; any is surrender.
Q What is a discriminated union?
A Each member carries a literal tag (kind: "circle" | "rect"); switching on the tag narrows the whole object at once. See the discriminated-unions entry.