🔷 TypeScript Q14 / 101

What is never type?

AI-Powered Answer ✓ Answered

The `never` type in TypeScript represents the type of values that never occur. It signifies a value that is impossible to reach or a function that will never complete its execution or successfully return a value. It's distinct from `void` and `undefined`.

What is the `never` type?

The never type is a bottom type in TypeScript, meaning it's a subtype of every other type. It's used for values that will never happen. This typically arises in two main scenarios: functions that throw an error (and thus never successfully return) or functions that contain an infinite loop. It also plays a crucial role in exhaustive checking for discriminated unions, helping to catch unhandled cases during development.

Functions that Never Return

When a function expression or an arrow function throws an error, or when it contains an infinite loop, TypeScript infers its return type as never. This indicates that the function will never reach its end to return a value.

typescript
function errorFunction(message: string): never {
  throw new Error(message);
}

function infiniteLoop(): never {
  while (true) {
    // This loop never terminates normally
  }
}

Exhaustive Checking with Discriminated Unions

A powerful use case for never is to ensure exhaustive checking in switch statements over discriminated unions. By assigning the default case to a never type variable, TypeScript can warn you if you've missed handling any variant of the union. If all variants are handled, the default case becomes unreachable, correctly typing never.

typescript
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; sideLength: number };
type Triangle = { kind: "triangle"; base: number; height: number };

type Shape = Circle | Square | Triangle;

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.sideLength ** 2;
    case "triangle":
        return 0.5 * shape.base * shape.height;
    default:
      const _exhaustiveCheck: never = shape; // If any case is missed, `shape` won't be `never` here, causing a compile-time error
      return _exhaustiveCheck;
  }
}

Difference from `void`

It's important to distinguish never from void. A function returning void means it returns undefined (implicitly or explicitly) and completes its execution normally. A function returning never means it *never* returns; its execution path is terminated by an error or an infinite loop, or it represents a state that should be impossible to reach.

When to use `never`

  • Declaring functions that are guaranteed to throw an error.
  • Declaring functions that are guaranteed to run in an infinite loop.
  • As a type for a variable that should conceptually never hold a value, often used for unreachable code paths in type-safe ways (e.g., exhaustive checking in switch statements).