Course contentsShow
← TypeScript
Lesson 1653 of 1,79638. Common Patterns and AntipatternsFree lesson

Discriminated Unions vs Flat String Unions

When to add a discriminant property instead of a union of 20 string literals.

Discriminated Unions vs Flat String Unions

You'll learn when to add a discriminant property instead of merging everything into one massive string literal union.

The Flat Union Approach

When modeling different states or types, you might be tempted to represent them as a flat union of string literals:

type FileStatus = 
  | "idle"
  | "uploading"
  | "uploadSuccess"
  | "uploadError"
  | "processing"
  | "processingSuccess"
  | "processingError"
  | "complete"
  | "deleted"
  | "archived";

This works for simple cases, but as your system grows to 20+ states, several problems emerge:

  • No structure: Everything is one flat list with no semantic grouping
  • No associated data: You can't attach error messages, progress percentages, or timestamps to specific states
  • Difficult narrowing: You must manually check strings with no help from the type system

The Discriminated Union Alternative

Instead, add a discriminant property that categorizes your states and allows each variant to carry relevant data:

type FileState =
  | { status: "idle" }
  | { status: "uploading"; progress: number }
  | { status: "success"; url: string; uploadedAt: Date }
  | { status: "error"; message: string; retryable: boolean };

function handleFile(state: FileState) {
  switch (state.status) {
    case "idle":
      // state is { status: "idle" }
      return "Waiting to start...";
    case "uploading":
      // state is { status: "uploading"; progress: number }
      return `Uploading: ${state.progress}%`;
    case "success":
      // state is { status: "success"; url: string; uploadedAt: Date }
      return `Available at ${state.url}`;
    case "error":
      // state is { status: "error"; message: string; retryable: boolean }
      return state.retryable ? "Retry available" : "Failed permanently";
  }
}

When to Choose Each

Use flat string unions when:

  • You truly have simple labels with no associated data
  • The list stays small (under 5-7 options)
  • All variants are treated uniformly

Use discriminated unions when:

  • Different states need different data
  • You have semantic groupings (loading states, error types, success variants)
  • You need exhaustive checking and type narrowing
  • The system is likely to grow in complexity

Key Takeaway: When your "states" need context or data, or when your string union approaches 20+ members, it's time to introduce a discriminant property and embrace discriminated unions for better structure, type safety, and maintainability.