Backbencher.dev

Never Type in TypeScript

Last updated on 23 Jan, 2023

never is a type that a function can return.

If you have a function that always throws an error, that function never returns a value.

function generateError(message: string) {
  throw new Error(message);
}

Since above function always throws an error, the function not even returns an undefined. So, in cases like this, we can specify the function to return never.

function generateError(message: string): never {
  throw new Error(message);
}

If you want to verify if the function does not return anything, try below code:

function generateError(message: string) {
  throw new Error(message);
}

const result = generateError("My error");
console.log(result);

Above code does not print anything in console.

--- ○ ---
Joby Joseph
Web Architect