Sub topic 8
Discriminated Unions in TypeScript
Prerequisites
This chapter assumes that you know basic TypeScript syntax, type aliases, functions, switch statements, and union types such as string | number. You should also understand that TypeScript checks which operations are valid for a value before the program runs.
A discriminated union is a union whose members share a property with different literal values. That shared property is the discriminant. TypeScript uses the discriminant to identify which member a value has.
For example, these types describe two possible results:
type Success = {
status: "success";
data: string;
};
type Failure = {
status: "failure";
error: string;
};
type Result = Success | Failure;Both members have a status property, but its value is different. The value "success" identifies Success, while "failure" identifies Failure.
Narrowing with the Discriminant
Check the discriminant before reading member-specific properties:
function describe(result: Result): string {
if (result.status === "success") {
return `Received: ${result.data}`;
}
return `Request failed: ${result.error}`;
}
console.log(describe({ status: "success", data: "User profile" }));
console.log(describe({ status: "failure", error: "Network unavailable" }));Inside the first branch, TypeScript knows that result is a Success, so result.data is valid. After the check fails, TypeScript knows that the value is a Failure, so result.error is valid.
The compiler follows the same rule with a switch statement:
type LoadingState = { state: "loading" };
type ReadyState = { state: "ready"; items: string[] };
type ErrorState = { state: "error"; message: string };
type PageState = LoadingState | ReadyState | ErrorState;
function render(state: PageState): string {
switch (state.state) {
case "loading":
return "Loading...";
case "ready":
return `Items: ${state.items.join(", ")}`;
case "error":
return `Error: ${state.message}`;
}
}
console.log(render({ state: "ready", items: ["Home", "Settings"] }));Each case narrows state to one union member. This keeps related data together and prevents invalid combinations.
flowchart TD
A[PageState value] --> B{Check state}
B -->|loading| C[LoadingState]
B -->|ready| D[ReadyState with items]
B -->|error| E[ErrorState with message]Designing Reliable Discriminated Unions
Use a required property with literal values such as "loading", "ready", or "error". Keep the property name and literal values consistent across all members.
| Good design | Problematic design |
|---|---|
| `state: "ready"` | `state?: "ready"` |
| Every member has `state` | Some members omit `state` |
| Each member has related fields | Fields are optional on every member |
Optional properties often weaken narrowing:
type BadResult = {
status: "success" | "failure";
data?: string;
error?: string;
};This type allows a value with status: "success" but no data. The type does not express the relationship between the status and its data. A discriminated union expresses that relationship directly.
Common Errors
Do not compare the whole object to a string:
function broken(result: Result): string {
// `result === "success"` checks the wrong value.
return result.status === "success" ? result.data : result.error;
}The check must read the discriminant property. Also avoid changing the discriminant to a general string, because TypeScript can no longer connect a particular value to a particular union member.
Exercise
What type does TypeScript assign to state inside the "ready" case in the render function?
Show answer
TypeScript narrows it to ReadyState, so state.items is available and state.message is rejected.