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.

GroupType Composition
KindType
Strict modeNot 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 | BMembers 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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏