Understanding the never Type in TypeScript
Discover the never type in TypeScript, which represents values that never occur. Learn about its use cases, including functions that throw errors or enter infinite loops, and how it helps in managing exceptional cases in your code.
TypeScript: The never Type
The never
type in TypeScript represents values that never occur. It's primarily used in two scenarios:
Understanding never
Functions that Never Return:
- Functions that throw an error.
- Functions that enter an infinite loop.
TypeScript Code: Functions with never Return Type
function error(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {
console.log('This loop never ends');
}
}
never vs. void
While both never
and void
represent the absence of a return value, there's a crucial difference:
void
functions can implicitly returnundefined
.never
functions guarantee that they will never return normally.
TypeScript Code: never vs void
function myVoidFunction(): void {
console.log('This function returns undefined implicitly');
}
let result1 = myVoidFunction(); // result1 is undefined
function myNeverFunction(): never {
throw new Error('This function never returns');
}
let result2: never = myNeverFunction(); // Error: Type 'never' is not assignable to type 'never'
never in Type Narrowing
When using type guards, if all possible types are eliminated, the resulting type is never
.
TypeScript Code: never in Type Narrowing
function isNumber(x: any): x is number {
return typeof x === 'number';
}
function doSomething(x: any) {
if (isNumber(x)) {
// x is definitely a number here
} else {
// x is never here, as all possible types have been eliminated
x; // Error: Type 'never' has no properties
}
}
Key Points
never
represents values that never occur.- Functions that throw errors or enter infinite loops have a return type of
never
. never
is a subtype of all types, but no type is a subtype ofnever
.void
functions can implicitly returnundefined
, whilenever
functions never return.
By understanding the never
type, you can write more precise and informative TypeScript code.