tipo-never-typescript

Use of Never in TypeScript

  • 3 min

The never type in TypeScript represents the set of values for functions that never return a valid value.

This generally means that the function throws an exception or enters an infinite loop and never completes its execution normally.

Although less common than types like string, number, or boolean, the never type plays an important role in managing cases that should not occur (such as errors or unreachable situations).

Some characteristics of the never type are:

  • It has no values: never does not accept values of any type.
  • Subtype of all types: never is a subtype of every other type. This means never can be assigned to any other type, but not the other way around.

How to use the never type

The never type is primarily used in two contexts:

  • Functions that throw exceptions or enter infinite loops
  • In control flow structures to handle unreachable cases.

Let’s see it with some examples.