Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of never keyword in typescript

Tags:

typescript

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.

like image 404
NeoAsh Avatar asked Feb 17 '17 07:02

NeoAsh


People also ask

What is never [] type?

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.

Why is variable type never TypeScript?

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.

What is the difference between never and void in TypeScript?

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.

When should I use unknown keyword TypeScript?

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.


1 Answers

  1. "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.

  1. "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" } 
  1. 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 
like image 200
Krzysztof Grzybek Avatar answered Sep 18 '22 20:09

Krzysztof Grzybek