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

never in Control Flow Analysis

How TypeScript uses never from throw functions to narrow types in remaining code paths.

never in Control Flow Analysis

You'll learn: How TypeScript uses never from throw functions to narrow types in remaining code paths.

What You'll Master

Control flow analysis is TypeScript's ability to track which code paths are possible. When a function returns never (like throwing an error), TypeScript knows that function never completes normally—so any code after it must be unreachable or the type narrowing changes.

How Throw Functions Affect Type Narrowing

When you call a function typed to return never, TypeScript removes that branch from its analysis. This affects type narrowing in powerful ways:

function assert(condition: boolean): asserts condition {
  if (!condition) throw new Error("Assertion failed");
}

function processValue(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  } else if (typeof value === "number") {
    console.log(value.toFixed(2));
  } else {
    assert(false); // TypeScript knows this is unreachable
    // After this point, value has type 'never'
  }
}

Even simpler—when TypeScript sees a throw function, it narrows the remaining type:

function fail(message: string): never {
  throw new Error(message);
}

function getLength(value: string | null) {
  if (value === null) {
    fail("Value cannot be null");
    // TypeScript knows execution stops here
  }
  
  // After the fail() call, TypeScript knows value is string
  return value.length; // No error—null is eliminated
}

Why This Matters

This pattern is incredibly useful for early validation. Instead of deeply nesting code with if-statements, you can throw early and TypeScript automatically narrows the remaining scope.

Key Takeaway: When TypeScript sees a function returning never, it eliminates that code path from type analysis, automatically narrowing types in subsequent code without explicit checks.