DEV Community

Cover image for Compile-Time vs Runtime Safety in React (TSX): The Power of never in TypeScript
Arka
Arka

Posted on

Compile-Time vs Runtime Safety in React (TSX): The Power of never in TypeScript

Compile-Time vs Runtime Implications of Invalid Values


📝 Context

TypeScript protects you at compile-time, but runtime is a different story. APIs may send unexpected values that break your app.


🚨 Without TypeScript – The Problem

function PaymentStatus({ status }) {
  if (status === "paid") return <p>Payment Successful</p>;
  if (status === "failed") return <p>Payment Failed</p>;
  // ❌ Forgot to handle "pending"
  return <p>Unknown Payment Status</p>;
}

// API sends "pending"
<PaymentStatus status="pending" />;
// UI incorrectly shows "Unknown Payment Status"

Enter fullscreen mode Exit fullscreen mode

✅ With TypeScript + never – Catch at Compile Time

type PaymentStatusType = "paid" | "failed" | "pending";

function PaymentStatus({ status }: { status: PaymentStatusType }) {
  switch (status) {
    case "paid":
      return <p>Payment Successful</p>;
    case "failed":
      return <p>Payment Failed</p>;
    case "pending":
      return <p>Payment is still processing...</p>;
    default: {
      const _exhaustive: never = status;
      return _exhaustive;
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

🎯 Takeaway

  • Compile-time: TypeScript forces you to cover "pending".
  • Runtime: Even if API sends "delayed", validation guards + never pattern prevent silent failures.

Top comments (0)