What is never in Typescript

avatar

Borislav Hadzhiev

Fri Feb 19 20212 min read

The never type is used very rarely in typescript, only when the function is never going to reach a return statement.

Which happens mostly for 2 reasons:

  • the function throws an error
  • the function loops infinitely

Let's look at an example of the most common use case - the function throws an error therefore it never reaches a return statement:

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

Notice

Not to be confused with the void type:

function logger(message: string): void { console.log(message); }

The difference being, void is used for a function that does not return anything, technically it can return null or undefined. If we accidentally return something from a function that returns void we would get an error message.

With the never type however a function is never going to return anything, so we annotate it with never to say we're never going to reach the end of this function. We're never going to execute the function completely.

It's very rare that we have functions that should be typed with never as a return value. For example if we only throw an error some of the time we shouldn't annotate the function with never:

function sometimesThrowError(message: string): number { if (!message) { throw new Error(message); } return 42; }

In the above scenario we should still annotate the function as returning a number and not never because there is a scenario in which the function reaches it's end and returns.

We only annotate a function with the type never, when it never reaches it's end. If it only possibly throws an error, we don't annotate it with never.

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee