Q5: What is the `never` type and how is it used for exhaustive type checking?

Difficulty:MediumTopic:Advanced Types

The never type represents values that never occur. It represents the return type of functions that never finish (e.g., throwing an error or running an infinite loop).

Because never is a assignable to every type, but no type is assignable to never (except never itself), it is used to perform Exhaustive Type Checking inside switch statements.

Exhaustive Switch-Case Checking
type Shape = { kind: 'circle' } | { kind: 'square' };

function getArea(s: Shape): number {
  switch (s.kind) {
    case 'circle': return Math.PI * 2;
    case 'square': return 4;
    default:
      const _exhaustiveCheck: never = s;
      return _exhaustiveCheck;
  }
}
💡 If a developer adds a new union member to Shape without handling it in the switch statement, TypeScript raises a compile-time error.
Key Takeaways
  • never signals unreachable code paths.
  • Assigning unhandled union cases to never guarantees total compile-time switch coverage.