Never type in typescript with example

Never type in TypeScript:

never type is a type of values that never occurs. For example, if a function always throws an exception or a function that will never return will be of never type.

never type is a subtype of every type also it can be assigned to every type. But reverse is not true. Only never can be assigned to never.

For example, below are examples of never type:

let throwError: never = (() => { throw new Error(`Throwing an error : `) })();

function runInfinite(): never {
    while(true){};
}

For the first one, it is throwing an Error and for the second one it runs a while loop for infinite amount of time. The infinite loop indicates that it will not reach to the end of the function. So, its return type is never.

never can be assigned to never:

For example,

let neverValue: never;

let neverFunction: never = (() => {
    while (true) { };
})()

Both of these will work. But,

let neverValue: never = 'hello';

this will not work.

Difference between void and never:

There are differences between void and never in TypeScript. We can have undefined or null value to a variable of void type but never can’t have any value.

We can also have the return value of a function as void type. The function can return null or nothing. If it doesn’t return anything, it will be of undefined type.

function getVoid(): void{
}

let one: void = null;
let two: void;

let three: void = getVoid();

console.log(one);
console.log(two);
console.log(three);

Here,

  • one is of void type and we are assigning value null.
  • two is of void type and we are not assigning any value to it. So, it will be undefined.
  • three is of void type and it is holding the value of getVoid function. This function is not returning anything. So, it will be undefined.

You might also like: