download

Why do separate UI booleans allow impossible screen states?

Frontend~7 minReviewed 3 Dec 2026Free · No sign-in

Question

After a failed retry, your store sets error: "Timeout" but forgets to reset isLoading: true. Because OrdersState keeps three separate fields (isLoading, error, items), TypeScript allows isLoading: true alongside error: "Timeout" and stale items. The banner stays stuck on "Loading..." and hides the failure.

  1. With three separate flags (isLoading, hasError, hasData), how many combinations exist versus valid screen states?
  2. Rewrite OrdersState as a discriminated union (idle, loading, error, ready).
  3. Update statusBanner with a never helper so adding a fifth state breaks compilation until handled.
"CODE · TYPESCRIPT"
type OrdersState = {
  isLoading: boolean;
  error: string | null;
  items: string[];
};

function statusBanner(state: OrdersState): string {
  if (state.isLoading) return "Loading...";
  if (state.error) return `Error: ${state.error}`;
  return `${state.items.length} orders`;
}
Show hints (3)
  1. "COUNT FLAG STATES"

    Three binary flags create 2^3 = 8 combinations. Only 4 screen states make sense, leaving 4 contradictory combinations like loading plus error.

  2. "TAG EACH VARIANT"

    Give every branch a literal status tag ("idle", "loading", "error", "ready") and attach message or items only where valid.

  3. "CHECK WITH NEVER"

    In switch (state.status), call assertNever(state) in default, where assertNever(x: never): never throws at runtime and fails compilation if any branch is missing.

Show checked explanation

Three separate flags create 8 combinations, even though only 4 UI states are valid. Replace them with a discriminated union tagged by status so each branch carries only its own fields. Switch on state.status and pass the default branch to assertNever(x: never) to catch missing cases at compile time.

"SOLUTION · TYPESCRIPT"
type OrdersState =
  | { status: "idle" } | { status: "loading" }
  | { status: "error"; message: string }
  | { status: "ready"; items: string[] };

function assertNever(x: never): never {
  throw new Error(`Unhandled state: ${JSON.stringify(x)}`);
}

function statusBanner(state: OrdersState): string {
  switch (state.status) {
    case "idle": return "Click Refresh";
    case "loading": return "Loading...";
    case "error": return `Error: ${state.message}`;
    case "ready": return `${state.items.length} orders`;
    default: return assertNever(state);
  }
}
console.log(statusBanner({ status: "error", message: "Timeout" }));
console.log(statusBanner({ status: "ready", items: ["A1", "B2"] }));
"OUTPUT"
Error: Timeout
2 orders

TypeScript starter and solution executed on Node.js v24.15.0 (native type-stripping, no tsc type-checker) across all four union states, contradictory boolean flags, and an unhandled runtime tag via Python 3.12.10; compile-time narrowing and never exhaustiveness checked against TypeScript 5 documentation. Checked by an editor other than the author.

Walkthrough

Three separate boolean flags (isLoading, hasError, hasData) allow 2^3 = 8 combinations. Only 4 represent real screens (idle, loading, error, ready). The other 4 are impossible states, such as isLoading: true with error: "Timeout". Worse, the starter shape cannot even separate "never fetched" from "fetched and found 0 orders".

VariantAllowed fieldsImpossible in this union
{ status: "idle" }status onlymessage or items
{ status: "loading" }status onlyerror hiding behind spinner
{ status: "error"; message: string }status, messageisLoading: true at same time
{ status: "ready"; items: string[] }status, itemsempty items confused with idle

How narrowing works. Every member shares the literal tag status. Inside case "error":, TypeScript narrows state to { status: "error"; message: string }. You can read state.message safely without null checks, and reading state.items becomes a compile error.

Why assertNever pays off later. After all four cases are handled, TypeScript narrows state in default to never. If a teammate adds { status: "refreshing"; items: string[] } next month and forgets statusBanner, TypeScript rejects assertNever(state) with a compile error because the "refreshing" variant is not assignable to never. Throwing inside assertNever also catches corrupted runtime tags cleanly instead of silently returning undefined.

Because each transition replaces the whole state object (setState({ status: "error", message: "Timeout" })), you can never forget to flip an old boolean back to false.

Common mistakes

  • Keeping optional fields on one flat type ({ status: Status; message?: string; items?: string[] }). That still allows { status: "loading", message: "Timeout" } and forces optional chaining everywhere.
  • Writing default: return "" in the switch. A catch-all fallback hides newly added union variants from the compiler.
  • Using status: string instead of string literals ("idle" | "loading" | "error" | "ready"). A wide string tag breaks narrowing inside switch.
  • Leaving items: [] to represent both idle and an empty server response. Users then see "0 orders" before the first fetch finishes.

Follow-up questions

  • "How do you model a background refresh where old items stay visible while a spinner shows?" Add an explicit fifth variant: { status: "refreshing"; items: string[] }. Because assertNever checks every switch, the compiler immediately points to every view that must render stale items plus a refresh indicator.
  • "What if a screen has two unrelated filters, like sort order and search text?" Keep orthogonal UI controls as separate fields beside the fetch union, such as { query: string; request: OrdersState }. Combine fields into one discriminated union only when they are mutually exclusive states.
  • "Does a union prevent invalid transitions like jumping straight from idle to ready without loading?" No. A discriminated union prevents invalid shapes, not invalid transition paths. Pair the union with a typed reducer that accepts explicit events (FETCH_START, FETCH_OK, FETCH_ERR) to restrict allowed transitions too.

What a strong answer covers

Counts the 8 flag combinations versus 4 valid states, designs a tagged OrdersState union with branch-specific fields, and uses assertNever(x: never) so future states fail compilation if unhandled.

Open in interactive practice deck →

Original OfferVibe question. TypeScript Discriminated Unions · TypeScript Exhaustiveness Checking.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.