Suggest an editImprove this articleRefine the answer for “What is a union type in TypeScript?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**A union type** is a type that can take one of several possible values of different types; it is denoted with the vertical bar operator `|`. **Key point:** `string | number` means "a string or a number" - unlike `&`, which denotes an intersection of types.Shown above the full answer for quick recall.Answer (EN)Image## What a **union type** is in TypeScript A **union type** is a type that can take **one of several possible values** (of different types). > In simpler terms: > A union lets you say: > "This variable can be **either this or that**". --- ## How a union type is written Union types are created with the **vertical bar operator** `|`. ```javascript let value: string | number; ``` This means: > `value` can be **a string** (`string`) **or a number** (`number`). --- ## Usage examples ### Example 1. A simple union of types ```javascript let id: number | string; id = 123; // a number is fine id = "123"; // a string is fine id = true; // error - not part of the union ``` --- ### Example 2. Union in function parameters ```javascript function printId(id: number | string) { console.log("ID:", id); } printId(42); // OK printId("abc123"); // OK ``` --- ### Example 3. Restricted string values (literal union types) ```javascript type Direction = "up" | "down" | "left" | "right"; let move: Direction; move = "up"; // ok move = "right"; // ok move = "forward"; // Error - "forward" is not part of the union ``` --- ### Example 4. A union with `null` and `undefined` ```javascript let username: string | null = null; function printName(name: string | undefined) { if (name) console.log(name.toUpperCase()); } ``` --- ## Remember | Concept | Description | |---|---| | **Union type** | A type that combines several other types | | **Operator** | ` | | **Example** | `string | | **Meaning** | "OR" - the value can be **one of the listed types** | --- ### A simple formula: > `|` is the logical **OR** for types > (unlike `&`, which means **AND** - "an intersection of types").For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.