Course contentsShow
← TypeScript
Lesson 383 of 1,7969. Union TypesFree lesson

Creating Simple Union Types

Combine two or more types with | to allow a variable to hold values of either type.

Creating Simple Union Types

You'll learn: How to combine two or more types using the | operator so a variable can hold values of different types.

What Are Union Types?

In the last lesson, you learned what union types are conceptually. Now you'll learn how to create them in practice.

A union type lets you say "this value can be Type A or Type B or Type C." You create unions by placing the pipe character (|) between types.

Basic Union Syntax

let id: string | number;

id = "abc123";  // ✓ Valid - string is allowed
id = 42;        // ✓ Valid - number is allowed
id = true;      // ✗ Error - boolean is not in the union

Here, string | number means the variable accepts either type.

Think of It Like "Either/Or"

Imagine a vending machine that accepts both coins or bills — not credit cards. A union type works the same way: it accepts values from a defined set of options, nothing else.

Combining Multiple Types

You're not limited to two types:

let status: "idle" | "loading" | "success" | "error";

status = "idle";      // ✓ Valid
status = "loading";   // ✓ Valid
status = "pending";   // ✗ Error - not in the union

This union includes four specific string literals.

Mixing Different Kinds of Types

let data: number | boolean | null;

data = 42;     // ✓ Valid
data = false;  // ✓ Valid
data = null;   // ✓ Valid

You can combine primitives, literals, or even object types — flexibility is the strength of unions.

Key Takeaway: Create union types with the | operator to allow a variable to accept values from two or more types, giving you controlled flexibility.