Skip to main content
D
TypeScript
TypeScript Union Types

TypeScript Union Types

Union types allow a variable to hold multiple specific types.

Read Time
5 min read
Difficulty
Beginner
Last Updated
Jun 15, 2026
Version
v1.0.0

Introduction

Sometimes a variable legitimately needs to handle two different types of data. For example, a phone number might be a number (`5551234`) or a formatted text string (`"555-1234"`). Union types solve this problem.

Example

Example
1/* this uses a union type */
2function printID(id: number | string) {
3  console.log("The ID is: " + id);
4}
5
6printID(101);
7printID("A-101");

Key Points

  • Use the pipe symbol `|` to create a union.
  • It means "either this OR that".
  • It gives flexibility without losing strict safety.
  • You often have to check the type before using the data.

Up Next

Continue your journey with the next topic.

Go to TS Intersection Types