TypeScript · Middle · Question 2 of 75

How do you guarantee that a switch handled every member of a union?

function area(s: Shape) {
  switch (s.kind) {
    case 'circle': return Math.PI * s.radius ** 2;
    case 'square': return s.size ** 2;
    default: { const _exhaustive: never = s; return _exhaustive; }
  }
}

Explanation

If you add a new shape to Shape and forget a case, a non-empty type remains in default, and assigning it to never causes a compile error. The noImplicitReturns flag and the ESLint rule switch-exhaustiveness-check also help.

Further reading

Problem with a question

TypeScript · Middle · question 2

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz