Type-Checking React Props With Discriminated Unions
Here we have a type of ModalProps
that takes in two possible variants: either no-title
or title
. Depending on the variant, it can either receive a title or not.
type ModalProps = { variant: "no-title" | "title" title?: string}
Inside the component, if it has a variant
Transcript
00:00 For this exercise, we're going to look at using a discriminated union to handle props in React and improve the types of props that we're passing into our components. Here we have a type of modal props and it takes in two possible variants, either no title or a title. And it can either receive a title or not.
00:19 And inside here, if it has a variant of no title, then it just returns an element with no title in it or it returns a title with props.title. Except this is fine inside of the component, but outside of the component, it's kind of lying to our consumers a little bit
00:37 because it's letting us pass various kind of impossible things in. So what it's letting us do is first of all, it's letting us pass in a variant of no title with a title attached. So ideally, what we should be getting here is an error if we try to pass in a title when we pass in no title.
00:54 And if we fail to pass in a title, it should be erroring at us as well. So this should be an error too. Your job here is to try to work out if you can find a way to change this type of modal props to better meet these goals. And I'll give you a clue. You're probably going to want to use a discriminated union for this.
01:14 I'll attach some resources below. Good luck.