The type never
in Typescript can be used when there is certainty that something will never happen. If you try to assign a value to a variable of type never
, the compiler will give you an error:
const a: never = 11;
//Type ’number’ is not assignable to type ’never'.
However, you can assign never to a function for example, which will never reach its end or will throw an exception:
function infiniteLoop(): never {
while (true) {
console.log("I will never end");
}
}
function throwAnError(): never {
throw new Error("Error! Something went wrong");
}
Difference between never
and void
A question that comes up is: What is the difference between never
and void
?
A function that has void
as its return, returns nothing while a function has never
as its return, returns never
.