Unions and Narrowing 28 exercises
explainer

The switch (true) Pattern in TypeScript

Another common pattern in switch statements that you might be familiar with is the switch (true). This pattern is reminiscent of an if statement but can be adapted to fit into a switch statement construct.

Here's what it looks like with the calculateArea function that uses switch instead of

Loading explainer

Transcript

00:00 Another pattern that you might be used to with switch statements is a switch true, which is kind of like an if statement, but can be kind of molded into a switch statement. So what we're saying here is switch true. That's interesting.

00:14 And then the thing that we pass into the case here is actually going to be the thing that we're checking to check if it's true or not. So sort of counterintuitive way of structuring your code, but it can be really, really useful when you have complicated sets of logic that you want to kind of fall into each other. So we've got our calculate area function.

00:34 Our calculate area function has the same kind of checks as it has before. But you notice here that it's still working even if we've got switch true. So we've got case shape.kind equals circle. Very clever. Then it gets narrowed properly into circle and shape.kind equals square gets properly narrowed too into a square. Beautiful stuff.

00:53 This is actually only been possible since TypeScript 5.3. And you might be reading this or watching this in the future. Currently, this is on the beta version of TypeScript, which is coming out. So you can see how TypeScript kind of evolves through time and adds these kind of new changes, which is super duper cool.

01:10 But anyway, this switch true also works really nicely with narrowing statements like this or discriminated unions like this and with other kinds of narrowing too. Very cool.