Lesson

TypeScript Union Types

10 min reading
Free Course

TypeScript Union Types: Flexible Inputs and Safe Narrowing

A TypeScript union type (|) lets a variable or parameter accept more than one possible type, such as string | number. When a value has a union type, TypeScript only allows operations valid for every member until you narrow it down.

Discriminated unions take this a step further by pairing a shared literal tag (like kind or status) so switch statements narrow complex objects cleanly.

Narrowing Unions with typeof and Discriminated Tags

Use typeof for primitive unions and a shared status literal tag for object unions:

function formatId(id: string | number): string {
  if (typeof id === "number") {
    return `ID-${id.toString().padStart(4, "0")}`;
  }
  return id.trim().toUpperCase();
}

type FetchResult =
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; message: string };

function renderResult(res: FetchResult): string {
  switch (res.status) {
    case "loading":
      return "Loading...";
    case "success":
      return `Loaded ${res.data.length} items`;
    case "error":
      return `Failed: ${res.message}`;
  }
}

console.log(formatId(42), renderResult({ status: "success", data: ["a", "b"] }));

Common Mistakes to Avoid

  • Calling .toUpperCase() directly on string | number: TypeScript rejects methods that do not exist on number until you narrow with typeof val === "string".
  • Modeling state with booleans instead of discriminated unions: Using { loading: boolean; error?: string; data?: Item[] } allows impossible combinations (loading: true and error set at once); discriminated unions make invalid states unrepresentable.
  • Confusing union | with intersection &: A | B means either A or B; A & B means must have all properties of both A and B.

Frequently Asked Questions

How do I handle optional nullability with unions?

Write User | null or string | undefined, and narrow with if (user !== null) or optional chaining user?.name.

What is a string literal union?

A type like type Theme = "light" | "dark" | "system" restricts a string variable strictly to those exact values without the runtime weight of an enum.

How does TypeScript know res.data exists inside case "success":?

TypeScript tracks control flow on the shared status literal field and automatically narrows res to { status: "success"; data: string[] } inside that branch.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum