- Learning TypeScript 2.x
- Remo H. Jansen
- 285字
- 2025-04-04 17:02:05
The never type
As described in the TypeScript documentation, the never type has the following characteristics:
- The never type is a subtype of and assignable to every type.
- No type is a subtype of or assignable to never (except never itself).
- In a function expression or arrow function with no return type annotation, if the function has no return statements or only return statements with expressions of type never and, if the end point of the function is not reachable (as determined by control flow analysis), the inferred return type for the function is never.
- In a function with an explicit never return type annotation, all return statements (if any) must have expressions of a type never and the end of the function must not be reachable.
In JavaScript, when a function doesn't explicitly return a value, it implicitly returns the value undefined. In TypeScript, the return type of such a function is inferred as void. When a function doesn't complete its execution (it throws an error or never finishes running at all), its return type is inferred as never by TypeScript:
function error(message: string): never {
throw new Error(message);
}
// Type () => never
const sing = function() {
while (true) {
console.log("I will never return!");
}
};
We can also encounter the never type when we reach impossible matches in discriminated unions:
function area(shape: Shape) {
const PI = Math.PI;
switch (shape.kind) {
case "square": return shape.size * shape.size;
case "rectangle": return shape.width * shape.height;
case "circle": return PI * shape.radius * shape.radius;
default:
return shape; // never
}
}
In the preceding code snippet, the default case will never be executed; therefore, the return type is inferred as the never type.