Sub topic 8
Modeling State So Invalid States Cannot Exist
This chapter assumes you know basic TypeScript syntax, can write if and switch statements, and compile with strict: true. It also assumes you have seen a discriminated union (an object type with a literal kind or status property) and how switch narrows it. Here you use that pattern to design application state so the compiler rejects impossible combinations.
The problem with a bag of optional fields
A common first attempt at modeling a network request looks like this:
interface LooseState<T> {
isLoading: boolean;
data?: T;
error?: Error;
}
const broken: LooseState<string> = {
isLoading: true,
data: "stale value",
error: new Error("boom"),
};
console.log(broken);This compiles. The object claims to be loading, to have data, and to have failed, all at once. Nothing in the type says which of those is true.
The type permits 2 × 2 × 2 = 8 combinations of "loading or not", "data present or not" and "error present or not". Only four of them mean something: not started, loading, succeeded, and failed. The other four are invalid states. Every function that reads this object must either guess which combination it received or defend against all of them. Those defenses are easy to forget, and the compiler does not remind you.
The fix is to make the type describe only the valid states, so the invalid ones cannot be written.
One variant per state
Give each valid state its own union member. Put a literal status property on every member as the discriminant, and attach each piece of data only to the member where it exists:
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function describe<T>(state: RequestState<T>): string {
if (state.status === "success") {
return `Loaded ${JSON.stringify(state.data)}`;
}
if (state.status === "error") {
return `Failed: ${state.error.message}`;
}
return state.status;
}Three things changed compared with the loose version:
dataexists only onsuccess. Readingstate.datawhile the state isloadingis a compile error, not a runtimeundefined.errorexists only onerror. A value cannot carry both, because no member declares both.- The boolean
isLoadingis gone. "Loading" is now astatusvalue, so it cannot disagree with the other fields.
In describe, the check state.status === "success" narrows state to the success member inside that block, which is why state.data is allowed there. After both if blocks return, TypeScript knows only idle and loading remain. Both have a string status, so return state.status type-checks.
Making transitions explicit
A union describes which states exist. A transition function describes how you move between them. Writing the transitions as a function that takes the current state and an action keeps every change in one place:
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
type Action<T> =
| { type: "fetch" }
| { type: "resolve"; data: T }
| { type: "reject"; error: Error }
| { type: "reset" };
function reduce<T>(
state: RequestState<T>,
action: Action<T>
): RequestState<T> {
switch (action.type) {
case "fetch":
return state.status === "loading" ? state : { status: "loading" };
case "resolve":
return state.status === "loading"
? { status: "success", data: action.data }
: state;
case "reject":
return state.status === "loading"
? { status: "error", error: action.error }
: state;
case "reset":
return { status: "idle" };
}
}
let state: RequestState<string> = { status: "idle" };
state = reduce(state, { type: "fetch" });
state = reduce(state, { type: "resolve", data: "hello" });
console.log(state); // { status: 'success', data: 'hello' }
state = reduce(state, { type: "resolve", data: "late duplicate" });
console.log(state); // unchanged: still the first successTwo details matter here.
First, Action<T> is itself a discriminated union, discriminated by type rather than status. The discriminant can have any name. Pick one name per domain and use it consistently.
Second, the resolve and reject cases ignore the action unless the state is loading. A late response that arrives after a reset is dropped instead of overwriting newer state. The type system cannot enforce this rule. You enforce it in the transition logic, but because the logic is in one function, you can test it in one place.
Always build a new object for each transition. Do not mutate state.status. Assigning state.status = "success" leaves any leftover error field in place, which reintroduces the invalid combinations you removed.
Data that belongs to several states
Real interfaces often need data to survive across states. Suppose you want to keep showing the old result while a refresh is in flight. Adding an optional data? to loading would bring back ambiguity, because you could not tell whether the first load or a refresh was running. Add a separate variant instead:
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "refreshing"; data: T }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function currentData<T>(state: RequestState<T>): T | undefined {
switch (state.status) {
case "refreshing":
case "success":
return state.data;
default:
return undefined;
}
}Stacked case labels narrow state to the union of the listed members. Both have data: T, so state.data is valid. Each new variant is a small cost, and it gives you an exact name for a situation you would otherwise describe with a combination of flags.
Invariants beyond loading and errors
The same idea applies wherever a field is only meaningful in some states. An order that has shipped has a tracking number. An order that has not shipped does not:
type Order =
| { status: "pending"; items: string[] }
| { status: "shipped"; items: string[]; trackingNumber: string }
| { status: "cancelled"; items: string[]; reason: string };
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
function summarize(order: Order): string {
switch (order.status) {
case "pending":
return `Waiting to ship ${order.items.length} item(s)`;
case "shipped":
return `Shipped, tracking ${order.trackingNumber}`;
case "cancelled":
return `Cancelled: ${order.reason}`;
default:
return assertNever(order);
}
}
console.log(summarize({ status: "shipped", items: ["pen"], trackingNumber: "ZX123" }));You cannot construct a shipped order without a tracking number, and you cannot read trackingNumber from a pending one. The assertNever default means that when someone adds a refunded variant, summarize stops compiling until it handles the new case.
Note that items repeats in every member. That repetition is deliberate. If it bothers you, define a shared base type and intersect it with each variant:
type OrderBase = { items: string[] };
type Order =
| (OrderBase & { status: "pending" })
| (OrderBase & { status: "shipped"; trackingNumber: string })
| (OrderBase & { status: "cancelled"; reason: string });Narrowing works the same way on the intersected members.
Design guidelines and trade-offs
- Start from the list of valid states, not from the list of fields. Write each state as a sentence ("a failed request has an error and no data"), then turn each sentence into a member.
- Replace boolean flags with a
statusvalue when the flags can be combined in meaningless ways. Keep a boolean only when it is truly independent of every other field. - Avoid optional properties as a way to express "only in some states". An optional property says the field may be missing in any state.
- Keep the number of variants proportional to the number of states people actually reason about. A union with a dozen members is a sign that two independent concerns have been merged. Split them into two separate state values instead of a product of both.
- Type checking covers compile-time code only. If state comes from
JSON.parse, local storage, or a network response, validate it before treating it as one of your variants. A later chapter covers this.
Exercise
Using the five-member RequestState<T> that includes refreshing, write a reduce-style case or function that handles a fetch action. It should move success to refreshing while keeping the data, move idle and error to loading, and leave loading and refreshing unchanged. Why does the refreshing variant make the invalid combination "loading with stale data of unknown origin" impossible?
Show answer
function startFetch<T>(state: RequestState<T>): RequestState<T> { switch (state.status) { case "success": return { status: "refreshing", data: state.data }; case "idle": case "error": return { status: "loading" }; case "loading": case "refreshing": return state; } } The data is only declared on refreshing and success, so a plain loading state has no data field to be stale. Whether data exists is part of the state name, so code that reads data must first narrow to a variant that declares it.