What is the difference between never and void in typescript?
In imperative languages, void
can be thought of as a type containing a single value. Such languages do not provide a means to construct or consume this value, but a void
function can be thought of as returning this trivial value.
In contrast never
is a type containing no values, which means that a function with this return type can never return normally at all. This means either throwing an exception or failing to terminate.
To augment Lee's very good answer, another way to think of it is that in a correctly-typed program, a never
value cannot be observed.
In addition to functions which never return (or which always throw exceptions), you'll see the never
type when a union type has been exhausted of all its possible constituents:
// Example assumes --strictNullChecks
function fn(x: number | string) {
if (typeof x === 'number') {
// x: number in this block
} else if (typeof x === 'string') {
// x: string in this block
} else {
// x: never in this block
// this block does not run; the value of x cannot be observed
}
}
In short:
void
returns void
, never
never returns.
As Marius Schulz discusses in this article,
- A function that doesn't explicitly return a value implicitly returns the value
undefined
in JavaScript. Although we typically say that such a function "doesn't return anything", it returns. We usually ignore the return value in these cases. Such a function is inferred to have avoid
return type in TypeScript.- A function that has a
never
return type never returns. It doesn't returnundefined
, either. The function doesn't have a normal completion, which means it throws an error or never finishes running at all.