Unions and Narrowing 28 exercises

Refactoring to a Switch Statement

The first step is to clear out the calcuateArea function and add the switch keyword and specify shape.kind as our switch condition. TypeScript's intelligence kicks in and suggests autocompletion for circle and square, based on the discriminated union.

Each case will be handled as they we

Loading solution


00:00 Okay, let's check out this CalculateArea function. We can remove all of this code. As soon as we remove it, all of our tests are going to break. But let's add a switch statement in here. And we're going to add shape.kind inside here. And now a couple of things happen. First of all, we get a case. And you notice, too, we're going to get autocomplete for caseCircle here.

00:21 Look at this. So caseCircle, and we've got caseSquare, too. So Timescript understands that shape.kind could be circle or square. So we get this gorgeous autocomplete for this, which is just below here, caseCircle. And so nice. And that's going to happen if you have 20, 40 members of your discriminated union. So we get caseCircle.

00:40 And now we can return the code that initially figured this out. So I'm going to just sort of skip over some code here and we get to this point here, where we have caseCircle return math.py shapeRadius and shapeRadius. And this is really cool. If we hover over this, too, you'll see that our function always returns a number. Isn't that clever?

01:01 So if we were to remove one of these or comment this out, you'd notice that we get number or undefined. But TypeScript understands here that we have shape.kind, which can either be circle or square, which means that any value passed into this, as long as it's a value of a valid kind, is going to hit one of these branches.

01:22 If we were to, let's say, just return or not return one of these, you notice that we don't get a fall-through here, unless we do a... Like, first of all, the thing we get back is always going to hit the square thing here, which doesn't seem right. But we can add a break inside here to make sure that it actually breaks. Because otherwise, inside square,

01:42 we would see something that's either circle or square. How clever is that? It understands all of the ways it can fall through. Gorgeous. But if we add a break here, of course, that's not going to happen. And if we add a break here, then this is going to be number or undefined. So TypeScript is so good with discriminated unions and switch statements. The final solution here is to have a return there

02:04 and a return inside here. Of course, we don't need to add these curly braces here, but we can if we want to. It means we can add, like, a multi-line code block in there. This works perfectly fine too, but lovely. So discriminated unions and switch statements are a match made in heaven.