Borislav Hadzhiev
Last updated: Feb 19, 2021
Check out my new book
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:
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); }
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
.