TypeScript Developer interview question · Most asked

What are discriminated unions and why are they powerful?

Summary

A discriminated (tagged) union is a union of object types sharing a literal property (the discriminant, e.g., type or status). Checking that property narrows to the exact variant, and exhaustiveness checks ensure every case is handled.

Longer Answer

They model state machines and API results precisely, making invalid states unrepresentable (e.g., { status: 'success'; data } vs { status: 'error'; error } instead of optional data? and error?). Combined with never-based exhaustiveness checks, adding a variant forces updates everywhere.

Code Example

type Result<T> =
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: Error };

function render(r: Result<string[]>) {
  switch (r.status) {
    case "loading": return "Loading…";
    case "success": return r.data.join(", ");
    case "error":   return r.error.message;
    default: {
      const _exhaustive: never = r;
      return _exhaustive;
    }
  }
}

Key Points

  • Shared literal tag field
  • Narrowing per variant
  • Exhaustiveness via never
  • Make invalid states unrepresentable

More most-asked TypeScript Developer questions

← All TypeScript Developer questions