Union Types

Value can be one of several types

#unions #types #type-aliases

Union Types

Union types allow a value to be one of several types.

Basic Union

type ID = string | number;

function printId(id: ID) {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id.toFixed(0));
  }
}

printId("abc-123");  // OK
printId(456);        // OK

Literal Unions

type Direction = "north" | "south" | "east" | "west";
type Status = "success" | "error" | "pending";

function move(direction: Direction) {
  console.log(`Moving ${direction}`);
}

move("north");  // OK
// move("up");  // Error: "up" not in union

Discriminated Unions

interface Circle {
  kind: "circle";
  radius: number;
}

interface Square {
  kind: "square";
  sideLength: number;
}

type Shape = Circle | Square;

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.sideLength ** 2;
  }
}

Discover another handy tool from EditPDF.pro