Common Pitfalls and Edge Cases
You'll learn how to avoid subtle mistakes that can undermine exhaustive matching and union type safety.
The Problem with Getting Complacent
Even after mastering exhaustive checks with discriminated unions, TypeScript beginners often stumble into traps that silently break type safety. These pitfalls typically happen when you're almost there but cut corners in ways that seem harmless.
Think of exhaustive checking like building a safety net—one small hole can let errors fall through, defeating the entire purpose.
Forgetting the Default Case
When using switch statements without an exhaustive check, developers sometimes simply forget to handle all cases. Without a default branch calling assertNever, new union variants added later won't trigger compiler errors:
type Status = "loading" | "success" | "error";
function handle(status: Status) {
switch (status) {
case "loading":
return "Loading...";
case "success":
return "Done!";
// Oops! Forgot "error" — no compiler error without default case
}
}
Using any Instead of never
A common mistake is declaring your exhaustiveness helper with any instead of never:
// Wrong!
function assertNever(value: any): never {
throw new Error(`Unexpected value: ${value}`);
}
With any, TypeScript won't catch missing cases because anything can be assigned to any. Always use never.
Ignoring Compiler Errors
Sometimes developers see a type error in the exhaustiveness check and suppress it with @ts-ignore or as any rather than fixing the root cause—usually a missing case. This defeats the entire safety mechanism.
Key Takeaway: Always use never (not any) for exhaustiveness helpers, include the default case with assertNever, and treat compiler errors as helpful signals rather than obstacles to silence.