Middle
What is the never type in TypeScript and how does it differ from other types?
sobes.tech AI
Answer from AI
The never type in TypeScript is used to denote values that never occur. It is a type for functions that never return a value (for example, they throw an error or run infinitely), or for variables that cannot have a value.
Differences from other types:
- Other types describe possible values, while
neverindicates the absence of values. neveris a subtype of all types, but no type is a subtype ofnever(exceptneveritself).
Example:
function error(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while(true) {}
}