Whether Throwing an Error Is Mandatory in Exhaustive Checks
📝 Context
A common misconception: never
means you must throw an error in default. Not true-you can choose how to handle it.
🚨 Without TypeScript – The Problem
function Page({ route }) {
switch (route) {
case "home":
return <p>Home</p>;
case "about":
return <p>About</p>;
// ❌ "contact" forgotten
default:
return null; // silently ignores
}
}
✅ With TypeScript + never – Alternatives
type Route = "home" | "about" | "contact";
function Page({ route }: { route: Route }) {
switch (route) {
case "home":
return <p>Home</p>;
case "about":
return <p>About</p>;
case "contact":
return <p>Contact</p>;
default: {
const _exhaustive: never = route;
// Options instead of crash:
console.error("Unexpected route:", route);
return <p>Redirecting...</p>;
// Or: toast("Invalid route");
// Or: navigate("/home");
}
}
}
🎯 Takeaway
-
never
enforces exhaustiveness, but how you handle it is up to you. - Options: return fallback UI, log error, redirect, show toast.
Top comments (0)