The never Type
Learn The never Type
never represents an impossible value or a control-flow path that cannot finish normally.
In this lesson, you will study the rule, run a complete TypeScript example, explain its output, and test a small change.
What you’ll learn
- Explain the main rule behind the never type.
- Predict the result of the complete runnable TypeScript example.
- Recognize one common mistake and correct it.
Understand the concept
A function that always throws can return never. TypeScript also uses never when analysis proves a branch is unreachable. Unlike void, never is not a placeholder for an ordinary missing return value.
Run a complete TypeScript example
Save this code as main.ts or paste it into the TypeScript Playground. The example uses fixed values so it runs without prompting for input.
TypeScript code
function fail(message: string): never {
throw new Error(message);
}
const score: number = 7;
console.log(score > 0 ? "Valid score" : fail("Invalid score"));Verified output
Valid scoreHow to run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. When using a project configuration, run the matching project build instead.
Trace the execution
The positive score chooses the first expression, so fail is never invoked in this run. If the alternative were evaluated, the throw would end normal execution.
Predict the output before you run the sample. Compare each line with the source expression that produced it, and distinguish the type checker’s work from what happens in JavaScript at runtime.
Common mistakes and how to avoid them
A never function cannot quietly reach the end. Do not annotate ordinary logging functions as never.
Debugging habit: when a change is rejected, read the exact compiler diagnostic and inspect the operand types. When it compiles but behaves unexpectedly, follow the values through the JavaScript expressions.
Practice it yourself
Set score to -1, run the example and observe the thrown error; then restore 7 to keep the lesson runnable without an exception.
Challenge: write down your prediction first, run the changed source, and explain any difference. Return to the verified version before continuing.
Check your understanding
Review the key idea
The never Type: A function that always throws can return never.
never represents no possible normal return value.
Before continuing, be able to explain what is checked before execution and what actually changes at runtime in the example above.
Reaching the recap and completing the quizzes are separate milestones.