Course contentsShow
← TypeScript
Lesson 952 of 1,79622. The never TypeFree lesson

Control Flow and Unreachable Code

How TypeScript uses never to mark code paths that can never execute after narrowing.

Control Flow and Unreachable Code

What You'll Learn

You'll learn how TypeScript uses the never type to identify and flag code paths that logically cannot execute after type narrowing.

The Core Idea

When TypeScript analyzes your control flow, it tracks which types are possible at each point in your code. Through narrowing (using guards like typeof, instanceof, or checking discriminated unions), TypeScript can determine when you've exhausted all possible cases. Any code after that point is unreachable, and TypeScript marks those locations with the never type.

Think of it like a maze with only one exit: once you've proven you've taken the only path out, there's nowhere else to go. TypeScript recognizes this impossibility and uses never to signal "this code should never run."

How TypeScript Detects Unreachable Code

When you narrow a type completely—handling every possible variant—TypeScript knows the code below is unreachable:

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

function handleStatus(status: Status) {
  if (status === "loading") {
    return "Please wait...";
  }
  if (status === "success") {
    return "Done!";
  }
  if (status === "error") {
    return "Failed!";
  }

  // TypeScript knows status is never here
  // All three possibilities were handled above
  status; // Type: never

  console.log("This line is unreachable"); // TypeScript warns about this
}

After handling all three string literals, status becomes never because there are no remaining possible values.

Practical Benefit: Catching Logic Errors

This detection helps catch bugs where you think you've covered all cases but haven't:

function processValue(value: string | number) {
  if (typeof value === "string") {
    return value.toUpperCase();
  }

  // If you forget to handle number, TypeScript doesn't mark this as never
  // because number is still possible
  value; // Type: number (not never - you missed a case!)
}

The absence of never tells you there's still work to do.

Dead Code After Returns

TypeScript also recognizes truly unreachable code after control flow statements:

function alwaysThrows(): never {
  throw new Error("Boom!");

  console.log("Never runs"); // TypeScript knows this is unreachable
}

function earlyExit(x: number) {
  if (x < 0) {
    return;
  }

  return x * 2;

  console.log("Unreachable"); // After return, nothing executes
}

Key Takeaway: TypeScript uses never to mark code paths that cannot execute after exhaustive narrowing or control flow statements, helping you identify dead code and verify you've handled all cases.