Unions and Narrowing 28 exercises
Problem

Adding Defaults to a Discriminated Union

We're back to the calculateArea function example:

function calculateArea(shape: Shape) {
  if (shape.kind === "circle") {
    return Math.PI * shape.radius * shape.radius;
  } else {
    return shape.sideLength * shape.sideLength;
  }
}

Until now, the test cases have involved ch

Loading exercise

Transcript

00:00 Okay, we are back with our calculateArea function. We have a square and a circle again, and we have added, though, a new test case. This new test case is right down the bottom here. And in our previous test cases, we're checking if you pass a kindCircle or a kindSquare,

00:17 then it should calculate the area properly using a discriminated union. But down here in the calculateArea function, it should calculate the radius when we don't pass in a member of the discriminated union, when we don't pass in a kind. So here we're sort of implicitly

00:32 saying when you don't pass a kind, you should treat it as if it were a circle. So here we're kind of like expecting a default behavior from our discriminated union. Hmm, interesting. Your job here is to try to find a way to express this, first of all, on the type level. So

00:50 in these types up here, you'll also probably need to change around some of the stuff in the function body to get the narrowing working in there. Good luck.