- “the never type represents the type of values that never occur.“
It might be return type of function that never returns:
const reportError = function () {
throw Error('my error');
}
const loop = function () {
while(true) {}
}
Here, both reportError and loop type is () => never.
- “Variables also acquire the type never when narrowed by any type guards that can never be true“
With operators like typeof, instanceof or in we can narrow variable type. We may narrow down the type the way, that we are sure that this variable in some places never occurs.
function format(value: string | number) {
if (typeof value === 'string') {
return value.trim();
} else {
return value.toFixed(2); // we're sure it's number
}
// not a string or number
// "value" can't occur here, so it's type "never"
}
- Common use case
Except better type safety (as in cases described above), never type has another use case – conditional types. With never type we can exclude some undesired types:
type NonNullable<T> = T extends null | undefined ? never : T;
type A = NonNullable<boolean>; // boolean
type B = NonNullable<number | null>; // number