Skip to main content

What is a union type in TypeScript?

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

ConceptDescription
Union typeA 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").

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.