Advanced Props 12 exercises

Discriminated Unions for Conditional Props in TypeScript

The solution is to use a discriminated union to handle the different behaviors based on a prop value.

We'll start by looking at the useStackBlitz version.

First, let's delete everything and set useStackBlitz to true. Notice that we're using the required version here, which means that when yo

Loading solution


00:00 So the solution here is to use a discriminated union. And what we're going to do then is we want to split these into two different categories. We're going to look at the useStackBlitz version first. Let me just actually delete all of this. We're going to say useStackBlitz and we're going to mark this as true.

00:16 And you notice that we're using the required version here. So when you pass useStackBlitz true, you also must pass in a stackBlitzId string. This means then that this first one is working here. We've got useStackBlitz and stackBlitzId, all good. Now we want to look at the second branch.

00:33 And the second branch, let's say that we have useStackBlitz false. I'm going to mark that for now. And it's going to be codeSandboxId and you must pass that in here. So what we can see here then is that most of our stuff is working.

00:52 This error is working correctly now, which is great. And except this one isn't working because useStackBlitz is missing in type codeSandboxId string but required in this. So what we also want to cover here is when you don't pass in a useStackBlitz false.

01:10 So what we could do is we could do this. We could say useStackBlitz, let's say when you don't pass it in, when we have an undefined there, now you have to pass in a codeSandboxId. And this now works, except we can actually split these into like the same branch here.

01:27 So just to cover this again, useStackBlitzId when it's true, require this. When it's false, require this. And when it's undefined or not passed, which is what this means, then codeSandboxId. But we can actually join these two together. And we can say codeSandboxId like this, make it optional.

01:47 And this will still work when we delete this branch. So this is the answer here. Because now what we're saying is whether it's true, it goes into this branch, or whether it's false or undefined or not passed, then it goes into that branch. You notice too that we can actually pass in useStackBlitz, let's say, undefined,

02:05 and it will work here. Really, really nice setup. So this is how you handle things where you want to toggle behavior on and off, just with a props interface.