TypeScript Data Type - Never
TypeScript introduced a new type never
, which indicates the values that will never occur.
The never type is used when you are sure that something is never going to occur. For example, you write a function which will not return to its end point or always throws an exception.
function throwError(errorMsg: string): never {
throw new Error(errorMsg);
}
function keepProcessing(): never {
while (true) {
console.log('I always does something and never ends.')
}
}
In the above example, the throwError()
function throws an error and keepProcessing()
function is always executing and never reaches an end point because the while loop never ends. Thus, never type is used to indicate the value that will never occur or return from a function.
Difference between never and void
The void type can have undefined or null as a value where as never cannot have any value.
let something: void = null;
let nothing: never = null; // Error: Type 'null' is not assignable to type 'never'
In TypeScript, a function that does not return a value, actually returns undefined. Consider the following example.
function sayHi(): void {
console.log('Hi!')
}
let speech: void = sayHi();
console.log(speech); // undefined
As you can see in the above example, speech
is undefined, because the sayHi
function internally returns undefined even if return type is void. If you use never type, speech:never
will give a compile time error, as void is not assignable to never.