TS documentation says:
the never type represents the type of values that never occur. Variables also acquire the type never when narrowed by any type guards that can never be true.
I didn't understand its usage, can anybody give me an answer with some examples.
The never type represents the type of values that never occur. For instance, never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns. Variables also acquire the type never when narrowed by any type guards that can never be true.
The never type is a type that contains no values. Because of this, you cannot assign any value to a variable with a never type.
There is a difference between void and never. A function that has the explicit return type of never won't allow returning undefined, which is different from a void function which allows returning undefined.
unknown is the type-safe counterpart of any . Anything is assignable to unknown , but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.
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
.
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" }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With