Sub topic 8
Modeling State So Invalid States Cannot Exist
Assume you know TypeScript object types, unions, functions, if statements, and switch statements. Also assume your project uses strict mode with "strict": true in tsconfig.json.
Application state often has several possible phases. A request might be idle, loading, successful, or failed. A plain object with optional properties can represent combinations that should never happen:
type UnsafeState<T> = {
status: "idle" | "loading" | "success" | "error";
data?: T;
error?: Error;
};This type allows a loading state with old data, or an error state with no error object. TypeScript cannot tell which properties are required for each status because every property is optional.
A discriminated union models each valid state separately. Each member has a literal-typed status property that identifies the member.
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function renderUsers(state: RequestState<string[]>): string {
switch (state.status) {
case "idle":
return "Select Search to begin.";
case "loading":
return "Loading users...";
case "success":
return `Found ${state.data.length} users.`;
case "error":
return `Could not load users: ${state.error.message}`;
}
}
const states: RequestState<string[]>[] = [
{ status: "idle" },
{ status: "loading" },
{ status: "success", data: ["Ada", "Lin"] },
{ status: "error", error: new Error("Network unavailable") }
];
for (const state of states) {
console.log(renderUsers(state));
}Inside each case, TypeScript narrows state to the matching union member. The success branch can read data, while the error branch can read error. The other branches do not expose those properties.
Why this prevents invalid combinations
The union describes alternatives, not a collection of independent optional fields. A value must match one complete member. Therefore, this object is valid:
const success: RequestState<number> = {
status: "success",
data: 42
};An object with status: "success" must provide data. An object with status: "error" must provide error. A loading object cannot accidentally claim to have either property as part of its type.
This design also makes state transitions explicit. A function that starts a request can return only the loading member:
function beginRequest(): RequestState<never> {
return { status: "loading" };
}
function finishRequest<T>(data: T): RequestState<T> {
return { status: "success", data };
}
function failRequest(error: Error): RequestState<never> {
return { status: "error", error };
}The never type here means that these transitions do not carry success data. The generic RequestState<T> still describes the complete state model.
Choosing state boundaries
Use a discriminated union when the states have different data, behavior, or allowed operations. It works well for network requests, authentication, editors, payment flows, and asynchronous jobs.
If two states always have the same fields and behavior, a single object type may be simpler. The goal is not to create a union for every status string. The goal is to make invalid combinations difficult or impossible to construct.
Exercise
Define a discriminated union for a file upload with idle, uploading containing a numeric progress, and failed containing an Error. Which property narrows the union?
Show answer
Use type UploadState = { status: "idle" } | { status: "uploading"; progress: number } | { status: "failed"; error: Error };. The status property is the discriminant.