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; }
}
}- ✓Correct answer: Assign the value in
defaultto a variable of typenever - 2Add a
// @ts-exhaustivecomment before theswitch - 3Enable the
strictSwitchflag incompilerOptions
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.