Exhaustiveness with Discriminated Unions
What you'll learn: How to use discriminant properties to ensure you've handled every possible variant in a union type.
The Core Idea
When working with discriminated unions, you want the compiler to guarantee you've covered every case. The discriminant property (a literal type that's unique to each variant) becomes the key that unlocks TypeScript's exhaustiveness checking. By narrowing on the discriminant in a control structure, TypeScript can detect when you've forgotten a variant—and that's where never shines.
How It Works
Each variant in your discriminated union has a unique discriminant value. As you narrow through those values (via if, switch, or other guards), TypeScript eliminates the handled variants from the union. When all variants are accounted for, the remaining type is never—the empty type.
If you add a new variant to the union later but forget to handle it, the remaining type won't be never anymore—it'll be the new variant. This triggers a type error, alerting you to the gap in your logic.
The Pattern in Practice
type Result =
| { status: "success"; data: string }
| { status: "error"; message: string }
| { status: "loading" };
function handleResult(result: Result): string {
switch (result.status) {
case "success":
return result.data;
case "error":
return result.message;
case "loading":
return "Please wait...";
default:
// result is never here if all cases are handled
const exhaustiveCheck: never = result;
return exhaustiveCheck;
}
}
If you later add | { status: "pending" } to Result but don't add a case "pending", the default branch will error: Type '{ status: "pending" }' is not assignable to type 'never'.
Key Takeaway: By leveraging discriminant properties and assigning the leftover cases to never, you turn potential runtime bugs into compile-time errors—ensuring you handle every variant, now and in the future.