Why do separate UI booleans allow impossible screen states?
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.
- With three separate flags (
isLoading,hasError,hasData), how many combinations exist versus valid screen states? - Rewrite
OrdersStateas a discriminated union (idle,loading,error,ready). - Update
statusBannerwith aneverhelper so adding a fifth state breaks compilation until handled.
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)
- "COUNT FLAG STATES"
Three binary flags create
2^3 = 8combinations. Only 4 screen states make sense, leaving 4 contradictory combinations like loading plus error. - "TAG EACH VARIANT"
Give every branch a literal
statustag ("idle","loading","error","ready") and attachmessageoritemsonly where valid. - "CHECK WITH NEVER"
In
switch (state.status), callassertNever(state)indefault, whereassertNever(x: never): neverthrows 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.
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"] }));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".
| Variant | Allowed fields | Impossible in this union |
|---|---|---|
{ status: "idle" } | status only | message or items |
{ status: "loading" } | status only | error hiding behind spinner |
{ status: "error"; message: string } | status, message | isLoading: true at same time |
{ status: "ready"; items: string[] } | status, items | empty 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 theswitch. A catch-all fallback hides newly added union variants from the compiler. - Using
status: stringinstead of string literals ("idle" | "loading" | "error" | "ready"). A widestringtag breaks narrowing insideswitch. - Leaving
items: []to represent bothidleand 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[] }. BecauseassertNeverchecks everyswitch, 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
idletoreadywithout 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 →