Union Types

View saved

Combine types with |

A union means "this or that." Narrow before using type-specific operations.

type Id = string | number;

function printId(id: Id) {
  console.log("ID:", id);
}

printId(42);
printId("abc-123");

Model status values

String literal unions document allowed choices better than a free-form string.

type Status = "idle" | "loading" | "done" | "error";

let state: Status = "idle";
state = "loading";
// state = "paused"; // Error

Use unions on properties

Optional fields and nullable values are common unions in real APIs.

interface Result {
  value: string | null;
}

const ok: Result = { value: "saved" };
const empty: Result = { value: null };

Plan for every branch

  • Handle each member of a union before assuming a shape
  • Prefer literal unions for finite sets of strings
  • Avoid giant unions when an interface or enum-like pattern is clearer
  • Combine with narrowing in the next lesson

Comments

One comment per signed-in account. Comments are saved with this page’s URL.