DEV Community

Cover image for Do You Always Need to Throw Errors in never Exhaustive Checks? (React + TSX Guide)
Arka
Arka

Posted on

Do You Always Need to Throw Errors in never Exhaustive Checks? (React + TSX Guide)

Whether Throwing an Error Is Mandatory in Exhaustive Checks


📝 Context

A common misconception: nevermeans 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
  }
}

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

🎯 Takeaway

  • neverenforces exhaustiveness, but how you handle it is up to you.
  • Options: return fallback UI, log error, redirect, show toast.

Top comments (0)