Unions

`A | B` — "Either A or B"

Unions

A union type allows several types. The bedrock of TS modeling — optional values, error cases, variants.

4 min read Level 1/5 #typescript#unions#types
What you'll learn
  • Author union types
  • Combine and nest unions
  • Recognize common union patterns

A union type is “either A or B” — a value can be one of several types.

The Basics

let id: string | number = "abc";
id = 42;             // ✓ — number is fine
id = true;            // ✗ — boolean isn't in the union

The | is the union operator.

Common Patterns

Optional values

let maybeName: string | null = null;
let maybeAge: number | undefined;

Multiple acceptable inputs

function pad(value: string | number) {
  return String(value).padStart(4, "0");
}

pad(42);     // "0042"
pad("12");   // "0012"

Variants

type Status = "pending" | "active" | "done" | "error";

A union of literal types — also called a string-literal union. Used constantly.

Operations on a Union

You can only use operations that work on every member of the union:

function shout(x: string | number) {
  x.toUpperCase();
//  ~~~~~~~~~~ Property 'toUpperCase' does not exist on type 'string | number'.
}

toUpperCase exists on string but not on number. To call it, narrow the type first (next few lessons):

function shout(x: string | number) {
  if (typeof x === "string") {
    x.toUpperCase();   // ✓ inside the branch, x is string
  }
}

Common Methods Across Members

When members share a method, you can call it directly:

function len(x: string | string[]) {
  return x.length;   // ✓ both have .length
}

Unions of Objects

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(s: Shape) {
  if (s.kind === "circle") {
    return Math.PI * s.radius ** 2;
  }
  return s.side ** 2;
}

That kind field is what makes it a discriminated union — the single best pattern in TS, covered in detail in a few lessons.

Up Next

The opposite operation — combining types with &.

Intersections →