Graceful Fallback Using never
Without Crashing
📝 Context
In production, you don’t always want to throw errors. Users deserve a graceful fallback instead of a crash.
🚨 Without TypeScript – The Problem
function Notification({ type }) {
switch (type) {
case "success":
return <p>Success!</p>;
case "error":
return <p>Error occurred</p>;
// ❌ "warning" missing
default:
throw new Error("Unhandled notification type");
}
}
// If API sends "warning" → app crashes
<Notification type="warning" />;
✅ With TypeScript + never – Graceful Fallback
type NotificationType = "success" | "error" | "warning";
function Notification({ type }: { type: NotificationType }) {
switch (type) {
case "success":
return <p>Success!</p>;
case "error":
return <p>Error occurred</p>;
case "warning":
return <p>Warning!</p>;
default: {
const _exhaustive: never = type;
// Instead of crashing → fallback
console.warn("Unexpected notification type:", type);
return <p>Something unexpected happened.</p>;
}
}
}
🎯 Takeaway
- Dev builds: Throw error to catch missing cases early.
- Prod builds: Provide fallback UI + log unexpected values.
Top comments (0)