TS7027Strict Mode
Since TS 1.8

Fix TS7027: Unreachable Code Detected

Learn why TypeScript throws TS7027 when allowUnreachableCode is false, why never-returning calls create dead code, and how to clean it up.

error TS7027: Unreachable code detected

What This Error Means

TS7027 means TypeScript found a statement that can never run. Something before it — a return, a throw, a break, a loop with no exit — already ends the flow, so execution never arrives at the line the compiler is pointing at. The code is not wrong in itself; it is simply dead.

The check lives behind the allowUnreachableCode compiler option, and that option has three settings rather than the usual two. Unset (the default) it reports a suggestion: your editor fades the dead code, but tsc stays silent and the build passes. Set to false the suggestion becomes error TS7027. Set to true the analysis is switched off entirely. This is why the error so often appears when you join a project or tighten a tsconfig.json, on code that was there all along.

function orderTotal(prices: number[]): number {
  return prices.reduce((sum, price) => sum + price, 0)
  console.log("summed", prices.length, "line items")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error: Unreachable code detected. (TS7027)
}

The analysis is structural, not type-driven. TypeScript builds a control-flow graph from the statements themselves — it does not need to know what prices holds. That distinction explains most of the surprises below: a literal if (false) is reported because the graph can see the branch is dead, while if (DEBUG_PANEL) with const DEBUG_PANEL = false is not, because that would require narrowing rather than flow structure.

Common Causes

All four samples below are compiled with --strict --allowUnreachableCode false. Without that second flag none of them report an error — you would only see the greyed-out hint in your editor.

1. Statements After return or throw

The everyday case, and usually the result of debugging: a return gets moved up to short-circuit a function and the logging line underneath is forgotten.

// ❌ Broken
function orderTotal(prices: number[]): number {
  return prices.reduce((sum, price) => sum + price, 0)
  console.log("summed", prices.length, "line items")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error: Unreachable code detected. (TS7027)
}
// ✅ Fixed — do the work before the function hands back its result
function orderTotal(prices: number[]): number {
  console.log("summing", prices.length, "line items")
  return prices.reduce((sum, price) => sum + price, 0)
}

A throw ends the flow in exactly the same way, so anything after throw new Error(...) in the same block is reported too. One thing that is not reported: a hoisted function declaration after a return. Declarations are lifted to the top of the scope before execution, so the compiler treats them as reachable even though they sit below the exit.

2. A Redundant break After return in a switch

Muscle memory from JavaScript switches: every case ends in break. When the case already returns, that break is dead code — the compiler points at the break, not at the case.

// ❌ Broken
type OrderStatus = "paid" | "shipped" | "cancelled"
 
function statusLabel(status: OrderStatus): string {
  switch (status) {
    case "paid":
      return "Payment received"
      break
//    ~~~~~~ Error: Unreachable code detected. (TS7027)
    case "shipped":
      return "On its way"
    default:
      return "Cancelled"
  }
}
// ✅ Fixed — a case that returns needs no terminator
function statusLabel(status: OrderStatus): string {
  switch (status) {
    case "paid":
      return "Payment received"
    case "shipped":
      return "On its way"
    default:
      return "Cancelled"
  }
}

The same shape shows up with continue in loops: continue followed by more statements in the same block, or a statement placed after break inside a case.

3. Code After a Call That Returns never

Since TypeScript 3.7 the flow analysis understands functions annotated never. A call to process.exit(), to an assertion helper, or to your own fail() wrapper ends the flow just like a throw — and everything after it becomes unreachable.

// ❌ Broken
function fail(message: string): never {
  throw new Error(message)
}
 
function loadUserProfile(userId: string): string | null {
  fail(`no profile source configured for ${userId}`)
  return null
//~~~~~~~~~~~ Error: Unreachable code detected. (TS7027)
}
// ✅ Fixed — fail() never returns, so there is nothing left to do
function fail(message: string): never {
  throw new Error(message)
}
 
function loadUserProfile(userId: string): string {
  fail(`no profile source configured for ${userId}`)
}

Note that the fixed version keeps its string return type and still compiles: because the end of the body is unreachable, the compiler does not ask for a value. If the helper does not always throw, the never annotation is the bug — type it void and the code below becomes reachable again. This only works for a plain call statement on a function with an explicit never return type; an inferred one does not count.

4. A Loop That Never Exits

A polling loop written as while (true) with a return inside it has no normal exit, so the guard statement underneath it can never run — which is awkward, because that guard is usually the only thing stopping the loop from spinning forever.

// ❌ Broken
async function waitForJob(jobId: string): Promise<string> {
  while (true) {
    const status = await fetchStatus(jobId)
    if (status === "done") {
      return status
    }
  }
  throw new Error(`job ${jobId} never finished`)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Error: Unreachable code detected. (TS7027)
}
// ✅ Fixed — give the loop a bound, and the timeout becomes reachable
async function waitForJob(jobId: string, maxAttempts = 10): Promise<string> {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const status = await fetchStatus(jobId)
    if (status === "done") {
      return status
    }
  }
  throw new Error(`job ${jobId} never finished`)
}

The related pattern is a try block that returns inside a try/finally pair with no other path out — code after the whole statement is unreachable, and so is anything after a literal if (false) guard used as a debug toggle.

How to Fix It

  1. Delete the dead statements, or move them. Nine times out of ten the line is a leftover and removing it is the whole fix. If it is still needed, move it above the return or throw that cut it off:

    console.log("summing", prices.length, "line items")
    return prices.reduce((sum, price) => sum + price, 0)
  2. Ask whether the control flow is the real bug. TS7027 often points at the symptom. A return that landed one line too early, a missing else, a break forgotten inside the loop above — fixing the flow makes the reported statement reachable again, which is what you actually wanted.

  3. Check the never annotations on your helpers. If the unreachable code sits after a call to an assertion or exit helper, confirm that the helper really never returns. A helper typed never that in fact falls through on some path will make perfectly live code look dead; type it void instead.

  4. Replace if (false) toggles with a real flag. Commented-out branches guarded by a literal false are reported; a const enableDebugPanel = false read by the same if is not, because the check is structural rather than type-based. A named constant (or an environment variable) documents the intent and keeps the branch compiling.

  5. Keep the check on — don't reach for allowUnreachableCode: true. Setting it to true silences the analysis project-wide, including the editor hint, and dead code is one of the cheapest bug signals you get. Set it to false in your tsconfig.json so unreachable code fails CI rather than quietly accumulating; reserve true for directories of generated output, and prefer scoping that to a separate config over flipping it globally.

FAQ

What causes TypeScript error TS7027?

TS7027 is reported when a statement cannot be reached by any path through its function and allowUnreachableCode is set to false. The compiler builds a control-flow graph from the syntax — statements after return, throw, break or continue, statements after a loop with no exit, bodies of a literal if (false), and statements after a call to a function annotated never. It does not use type narrowing to decide this, which is why a boolean constant that happens to be false does not trigger it.

How do I fix unreachable code detected in TypeScript?

Start by deleting the statement — most of the time it is a leftover from debugging and nothing depends on it. If the code is meant to run, the flow above it is wrong: move the statement before the return, add the missing else, or give the loop an exit condition. Where the dead code follows a helper call, check that helper's return type:

// fail() is annotated never, so everything after this call is dead
fail("unsupported payment provider")

Changing that annotation to void is the right fix when the helper can in fact return. Casting or @ts-expect-error would only hide the diagnostic without making the line execute.

Why does TypeScript grey out my code but not fail the build?

Because allowUnreachableCode defaults to undefined, which is a third state rather than a synonym for true. In that state the compiler still performs the analysis and reports the result as a suggestion: VS Code and other editors fade the dead code, while tsc exits zero and your build stays green. Dead code is often deliberate while debugging, so TypeScript opts not to break the build by default. To make it a real error add "allowUnreachableCode": false to compilerOptions — note the value is false, which reads backwards until you remember the option is named for what it permits. The check itself dates back to TypeScript 1.8, where unreachable code was an error by default; the softer suggestion-by-default behaviour came with the three-state option it has today.

Related Errors

Practice This

Browse all TypeScript practice challenges to keep sharpening your type-level skills.

Share this reference

Become a TypeScript Pro

Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.

Or start solving right away: explore all TypeScript challenges