TypeScript ยท Chapter 12 of 44

TypeScript Union Types

A union type allows a variable to hold one of several specified types, written by separating the types with a vertical bar `|`. This is useful when a value can legitimately be more than one type.

When working with a union, TypeScript only allows you to use operations that are valid for every type in the union, unless you first narrow the type down to one specific option.

Syntax
let id: string | number;
id = 101;
id = "A101";

Declaring a union

You write a union type as `string | number`, meaning the value can be either a string or a number. Function parameters commonly use unions to accept flexible input.

Using union values safely

Before calling type-specific methods, you typically check the type with `typeof` or another narrowing technique so TypeScript knows exactly which type you're working with.

Example 1 (typescript)
function printId(id: string | number) {
  console.log(`ID: ${id}`);
}
printId(101);
printId("A101");
Output
ID: 101
ID: A101

The function accepts either a string or a number thanks to the union type.

Example 2 (typescript)
function formatId(id: string | number): string {
  if (typeof id === "number") {
    return id.toFixed(0);
  }
  return id.toUpperCase();
}
console.log(formatId(5));
console.log(formatId("abc"));
Output
5
ABC

A typeof check narrows the union so the correct type-specific method can be called safely.

Key points

  • Union types are written with a vertical bar, like string | number.
  • A union value can hold any one of the listed types.
  • You must narrow a union before using type-specific methods.
  • Unions make functions more flexible while staying type-safe.
๐Ÿ’ก Note: Union types are one of the most commonly used features in real-world TypeScript code.

๐Ÿ“ Quick Quiz

1. How do you write a union of string and number?

2. What must you do before calling a type-specific method on a union value?

3. What can a variable of type `string | number` hold?