Course contentsShow
← TypeScript
Lesson 422 of 1,7969. Union TypesFree lesson

The assertNever Helper Function

Creating a reusable assertNever utility that accepts never and throws at runtime if called unexpectedly.

The assertNever Helper Function

You'll learn: How to create a reusable assertNever utility that catches missing union cases at both compile-time and runtime.

Making Exhaustiveness Checks Reusable

In the previous lesson, you saw the pattern of assigning a never variable to catch missing union cases. Rather than repeat that pattern everywhere, you can create a helper function that encapsulates this logic and provides better error messages.

The assertNever Function

Here's the standard implementation:

function assertNever(value: never): never {
  throw new Error(`Unexpected value: ${value}`);
}

This function accepts a parameter typed as never and returns never. If you call it with a value that isn't never, TypeScript will error at compile-time. If it somehow runs at runtime (due to incorrect types or JavaScript calling it), it throws an error.

Using assertNever in Switch Statements

type Status = "idle" | "loading" | "success" | "error";

function handleStatus(status: Status): string {
  switch (status) {
    case "idle":
      return "Not started";
    case "loading":
      return "Loading...";
    case "success":
      return "Done!";
    default:
      return assertNever(status); // Compile error if we forgot "error"!
  }
}

If you forget to handle "error", TypeScript sees you're trying to pass "error" (a string) to a function expecting never, and it flags the error immediately.

Why This Helps

The assertNever helper makes exhaustiveness checking consistent across your codebase and provides clear runtime errors if type safety fails. It's a tiny utility with outsized value for maintaining union type safety.

Key Takeaway: The assertNever helper function centralizes exhaustiveness checking, providing both compile-time type errors and descriptive runtime errors when union cases are missed.