Open In App

Explain the purpose of never type in TypeScript

Improve
Improve
Like Article
Like
Save
Share
Report

In Typescript when we are certain that a particular situation will never happen, we use the never type. For example, suppose you construct a function that never returns or always throws an exception then we can use the never type on that function. Never is a new type in TypeScript that denotes values that will never be encountered.

Example 1: The null can be assigned to void but null cannot be assigned to never type variables, nor can any other type be assigned including any.

Javascript




let variable: void = null;
let variable1: never = null;      // error
let variable2: never = 1;         // error
let variable3: never = "geek";     // error
let variable4: never = true;     // error


Output: No value of any other type can be assigned to a variable of never type.

error TS2322: Type 'null' is not assignable to type 'never'  ...
error TS2322: Type 'number' is not assignable to type 'never' ...
error TS2322: Type 'string' is not assignable to type 'never' ...
error TS2322: Type 'boolean' is not assignable to type 'never' ...

Example 2: Using never type in a function

A function that returns “never” must never have an endpoint, an infinite loop is an example of such a situation where the program never stops executing. In the below code there’s a for loop without a beginning and an end. we get nothing as the output.

Javascript




function infiniteLoop(): never {
  for (;;) {}
}
  
// Function call
infiniteLoop();


The function greet() never stops executing it continuously displays “hello” and it returns nothing so never type is used.

Javascript




function greet(): never {
  while (true) {
    console.log("hello");
  }
}
  
// Function call
greet();


Output: As discussed never type must be used only when the functions return nothing or never stop executing, in the output hello repeats infinitely. 

hello
hello
hello
......

Example 3: Using the never type in a function that throws an exception

In the below code throwTypeerror() function returns nothing but raises an error so the type of the function is never. the type of func() is also never as it calls the throwTypeerror() function which returns nothing.

Javascript




function throwTypeerror(str: string): never {
  throw new TypeError(str);
}
  
// Return type of this function is "never"
function func() {
  return throwTypeerror("a type error is being raised");
}
  
// Function call
func()


Output: The func() calls the throwTyperror() function, that function throws an error without returning anything, so both the functions are of the never type.

throw new TypeError(str);
TypeError: a type error is being raised

Reference: https://www.typescriptlang.org/docs/handbook/basic-types.html#never



Last Updated : 02 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads