DEV Community

Cover image for Graceful Fallbacks in React (TSX) with TypeScript’s never Type (Without Crashing Your App)
Arka
Arka

Posted on

Graceful Fallbacks in React (TSX) with TypeScript’s never Type (Without Crashing Your App)

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" />;

Enter fullscreen mode Exit fullscreen mode

✅ 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>;
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

🎯 Takeaway

  • Dev builds: Throw error to catch missing cases early.
  • Prod builds: Provide fallback UI + log unexpected values.

Top comments (0)