Advanced Props 12 exercises
solution

Destructuring vs Accessing Discriminated Union Props

Here's the initial code we're working with:


type ModalProps =
| {
variant: "no-title"
}
| {
variant: "title"
title: string
}
export const Modal = ({ variant, title }: ModalProps) => {
if (variant === "no-title") {
return <div>No title</div>
} else {

Loading solution

Transcript

00:00 Let's try a couple of different approaches here. First, what we're going to try and do is take this title and instead of just having title here, let's go dot dot dot props. Let's imagine that we really want to destructure up in here. And now props, let's see if we can do props dot title here. Nothing. Okay, why is that?

00:19 Props is okay. It's either an empty object or it's this title here. So title is present in one of the branches but not the other. This means that TypeScript basically will ignore the fact that title exists and you

00:33 would have to do something like else if, let's say title in props. Now it will understand that props is that branch of the other one, whereas the other. But really it should be narrowing that already.

00:49 Now this is a slight limitation in TypeScript which is that if you separate the discriminator from the rest of the thing that it's discriminating, then it basically won't apply what it understands about this to the rest of the props.

01:05 The only way to really get this working is to do this and say props dot variant and now it understands that the thing you're narrowing is that props. Whereas if you were to split them out into two different variables, then it wouldn't understand.

01:19 So if we do like const my props or let's say underscore props up here equals props, then we can't access underscore props here because this one hasn't been narrowed, this one has. And TypeScript's control flow isn't quite smart enough to pick that up.

01:37 So if you're really keen on doing destructuring, then the best way to do it is just to do it inside here because now it understands that inside this scope that props is the one with the title so you can do const title equals props and this is absolutely fine.

01:54 But my preferred solution is really just the one that we started out with which is just to have the props kind of at the top level and just access them based on there because it's really not too much pain and it means that if you're using this discriminated union props, it's going to be the same kind of everywhere you use it. Whereas this solution is perfectly fine if you want to do destructuring or if you have,

02:14 you know, you're doing a big refactor or something and the previous component was destructured. But I would always prefer to just access it off the props.

02:22 It's nice and simple.