Sub topic 11
Modeling states in code
This chapter assumes you know basic UI components, asynchronous data fetching, HTML, and TypeScript. The goal is to make the code reflect the states that your screen can actually have.
Turn states into a discriminated union
A data-driven screen usually has several states:
| State | Meaning | Data available |
|---|---|---|
| `loading` | The request is in progress | No |
| `error` | The request failed | Usually no |
| `success` | The request completed | Yes, possibly an empty list |
A discriminated union is a TypeScript type made from several object shapes. Each shape has a shared field, called a discriminant, that identifies which shape it is. Here, status is the discriminant.
type AsyncState<T> =
| { status: "loading" }
| { status: "error"; message: string; retryable: boolean }
| { status: "success"; data: T };
function renderList(state: AsyncState<string[]>): string {
switch (state.status) {
case "loading":
return "Loading projects…";
case "error":
return state.retryable
? `${state.message} Try again.`
: state.message;
case "success":
return state.data.length === 0
? "No projects yet. Create your first project."
: state.data.join(", ");
}
}
console.log(renderList({ status: "loading" }));
console.log(renderList({ status: "success", data: [] }));
console.log(
renderList({
status: "error",
message: "The project service is unavailable.",
retryable: true
})
);When the code checks state.status, TypeScript narrows the type. Inside the error case, state.message and state.retryable are available. Inside the success case, state.data is available.
The empty state is represented by success with an empty array. This matters because an empty result is not a failed request. The server answered successfully; it simply found no items.
Prevent impossible combinations
A weak state type often uses optional fields:
type WeakState<T> = {
loading: boolean;
error?: string;
data?: T;
};This type permits combinations that should not exist:
loading: truewith an error messageloading: falsewith neither data nor an error- data and an error at the same time
- an error without knowing whether retrying is useful
The discriminated union prevents these combinations during development:
type ProjectState =
| { status: "loading" }
| { status: "error"; message: string; retryable: boolean }
| { status: "success"; data: string[] };
const invalidState: ProjectState = {
status: "error",
message: "Request failed",
retryable: true,
data: []
};The last assignment produces a TypeScript error because an error state cannot also contain data. This catches a design problem before it becomes a rendering bug.
Model state transitions explicitly
The state type describes a snapshot. A transition describes how the screen moves from one snapshot to another.
A request normally enters loading, then reaches either success or error. Within success, the interface chooses between content and an empty state based on the data. A retry should return to loading; it should not silently leave the previous error visible while a new request runs.
For more complex screens, model independent regions separately. For example, a page could have a loaded project list while its activity panel is loading. One giant union for the whole page would force unrelated regions into the same state. Separate AsyncState values make partial updates possible without inventing false states.
Render every member
When adding a new state, update the type and the rendering logic together. An exhaustive helper can make missing cases a compile-time error.
function assertNever(value: never): never {
throw new Error(`Unhandled state: ${JSON.stringify(value)}`);
}
function renderProjects(state: AsyncState<string[]>): string {
switch (state.status) {
case "loading":
return "Loading projects…";
case "error":
return state.retryable
? `${state.message} Try again.`
: state.message;
case "success":
return state.data.length === 0
? "No projects yet. Create your first project."
: state.data.join(", ");
default:
return assertNever(state);
}
}The default branch can run only if state has a value not covered by the cases. If you later add { status: "refreshing"; data: T }, TypeScript will report an error until this function handles it.
Test the state model
Create at least one test or manual fixture for every union member:
- loading with no data
- retryable error
- non-retryable error
- success with items
- success with an empty collection
These fixtures should verify both the visible content and the available action. A retryable error should expose retry, while a non-retryable error should explain the next support or recovery path instead.
Exercise
Why should an empty list usually be modeled as success rather than error?
Show answer
The request completed successfully. The absence of items is valid data, so the success state can choose an empty-state message and action without pretending that the request failed.