Skip to content

Union Type

In one line

A union type (A | B) represents a value that can be either type A or type B. The pipe symbol | reads as 'or'.

In simple words

A union type lets a value be one of several types. You write it with the pipe symbol: string | number means the value is either a string or a number. This is one of TypeScript's most powerful features.

Unions are useful for function parameters that accept multiple types, for representing results that can be different shapes (like a success or error response), and for defining a set of allowed string values (string literal unions).

When you have a value of a union type, TypeScript only lets you access properties that exist on ALL types in the union. To access type-specific properties, you need to narrow the type using type guards (typeof, instanceof, or user-defined guards).

Example

typescript
function format(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase(); // narrowed to string
  }
  return value.toFixed(2); // narrowed to number
}

format("hello"); // "HELLO"
format(3.14159); // "3.14"

The parameter can be string or number. typeof narrows the type in each branch.

Common confusions

  • Confused with: intersection type

    The difference: Union (A | B) means 'either A or B'. Intersection (A & B) means 'both A and B simultaneously'.

Related terms

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary