Yashotantra Academy logo
← TypeScript theorytheory 0/50 · 0%
level 1
Curious · 0 XP
streak
0d
perfect
0
badges
0

100 XP to Apprentice

Control flow · medium

22. never and exhaustiveness checks

Using the empty type to catch missing switch cases.

1 min read3 questionsup to 50 XPtopic 22/50

Read in another language

AI translates the explanation and quiz text while preserving code and answer scoring.

`never` represents a value that can never occur — the return type of a function that always throws, or the type of a variable that has been narrowed to nothing.

ts
function assertNever(x: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(x)}`);
}

type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.r ** 2;
    case "square": return shape.s ** 2;
    default: return assertNever(shape);
  }
}

If someone adds a new `Shape` variant but forgets a case, `shape` in the `default` branch will no longer be `never`, and passing it to `assertNever` produces a compile error — turning a missed-case bug into a build failure instead of a runtime surprise.

How to study this topic

  1. 1. Read the explanation once end to end, skipping the code.
  2. 2. Re-read the code snippets and say out loud what each line does.
  3. 3. Answer the quiz without scrolling back — that is the real check.
  4. 4. Read every explanation, even for the answers you got right.

Scoring

  • · Up to 30 XP from quiz accuracy.
  • · +15 XP for a perfect first attempt.
  • · +5 XP while a 3-day streak is running.
  • · 75% or higher marks the topic complete.

Check your understanding

  1. 1. What does the `never` type represent?

  2. 2. How does `assertNever(shape)` in a `default` case help?

  3. 3. What is the return type of a function that always throws?

Badges

First light
Pass your first topic
Sharp shooter
3 perfect first-try quizzes
On a roll
Study 3 days in a row
Week warrior
Study 7 days in a row
Grinder
Earn 500 XP
Deep diver
Earn 1500 XP