Unions and Narrowing 28 exercises
Problem

Narrowing a Discriminated Union with a Switch

We're back with the version of the calcuateArea function that uses an if-else statement to calculate the area of a circle or square without doing any destructuring:

function calculateArea(shape: Shape) {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius * shape.rad
Loading exercise

Transcript

00:00 We're back here with our circle and square setup with our CalculateArea function, where we're still checking to see if Math.py is the right shape and we've got the right radius, and we're still handling squares too. We've got our discriminated union at the top. Nothing has really changed. We're not doing any of the destructuring that we were doing before.

00:18 It's all the same. But I want you to refactor this code. I would like you to refactor the CalculateArea function, just the stuff inside the function body, to use a switch statement instead of an if-else statement. This, I think, is going to make this thing a lot easier

00:33 to maintain going forward when we add, like, let's say we need to add 20 or more shapes. We want this to be easy to extend, and currently this if-else statement might get a little bit unwieldy. And it feels like the shape.kind equals circle, shape.kind equals triangle, shape.kind equals whatever, that's going to get a bit tiresome. So, your job, figure out

00:53 how to refactor the code inside the function body to use a switch statement instead, while still preserving all the behavior, and also investigating how TypeScript narrowing works in that switch statement. Good luck.