What is the difference between never and void in typescript?
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 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.