allowUnreachableCode: Controlling Dead Code Detection
What you'll learn: How to configure TypeScript's behavior when it detects code that can never execute after return, throw, or other flow-terminating statements.
What Is Unreachable Code?
Unreachable code is code that the compiler knows can never execute because control flow will never reach it. This typically happens after statements like return, throw, infinite loops, or functions that return never.
function greet(name: string): string {
return `Hello, ${name}`;
console.log("This will never run"); // Unreachable!
}
TypeScript's control flow analysis is smart enough to detect these situations and can warn you about them.
The allowUnreachableCode Flag
The allowUnreachableCode compiler option controls what TypeScript does when it finds unreachable code. It has three possible values:
undefined(default): Shows a grayed-out warning in your editor but doesn't cause compilation errorstrue: Silences all unreachable code detection completelyfalse: Treats unreachable code as a compilation error
// tsconfig.json
{
"compilerOptions": {
"allowUnreachableCode": false
}
}
Why This Matters
Unreachable code usually indicates a bug or misunderstanding in your logic. Consider this example:
function processStatus(status: string): number {
if (status === "active") {
return 1;
console.log("User is active"); // Never runs
}
return 0;
}
The console.log was probably intended to run before the return, but it never will. With allowUnreachableCode: false, TypeScript will error on this, forcing you to fix it.
Common Scenarios
Unreachable code appears after:
returnstatementsthrowstatements- Functions that return
never(likeassertNever) - Infinite loops
Setting allowUnreachableCode: false helps catch these mistakes during development rather than discovering them later through missing logs or unexecuted cleanup code.
Key Takeaway: The allowUnreachableCode flag lets you decide whether TypeScript should error, warn, or ignore code it knows can never execute—setting it to false provides an extra safety net against logic errors.