Unreachable Code After never
You'll learn: Why TypeScript marks code as unreachable after a function that returns never, even though it still type-checks that code.
The Paradox of Unreachable Code
When you call a function that returns never (like one that always throws an error or exits the process), TypeScript knows that line is a terminal point—execution will never continue past it. Any code following that call is logically unreachable.
Here's the interesting part: TypeScript still type-checks that unreachable code, but marks it with a warning that it will never execute.
Why Type-Check Dead Code?
Think of it like a proofreader checking a paragraph that's been crossed out. Even though the paragraph won't appear in the final document, the proofreader still corrects the grammar and spelling. Why? Because:
- The code might be reached during refactoring — You might move it elsewhere
- It reveals developer confusion — Maybe you didn't realize the function never returns
- Type errors are still errors — Even dead code should be syntactically valid
function fail(message: string): never {
throw new Error(message);
}
function processUser(id: number) {
if (id < 0) {
fail("Invalid ID");
// Everything after this is unreachable
console.log("This will never print"); // TS warns: unreachable code
const x: string = 123; // TS error: type mismatch (still checked!)
}
return "User processed";
}
TypeScript grays out the unreachable code and warns you, but it doesn't skip type-checking it. The assignment const x: string = 123 still produces a type error even though it can never run.
The Practical Impact
This behavior helps you catch mistakes. If you accidentally write unreachable code, TypeScript alerts you. If that unreachable code also has type errors, you know there's either a logic problem (shouldn't be unreachable) or dead code to delete.
Key Takeaway: Code after a never-returning function is marked unreachable by TypeScript but still fully type-checked, helping you maintain code quality even in paths that never execute.