Generics vs Discriminated Unions
Let's explore an interesting scenario where generics might not be as beneficial as another approach.
Here we have a
ModalProps type that takes in a type argument of
TVariant that extends
PossibleVariants. This means when using
ModalProps, we can only pass in
'with-button' or `'without-but
00:00 In this exercise, we're going to take a look at an example where generics are actually not as helpful as a different way of doing things. So here we have a type of modal props. Modal props takes in a type or type argument of T variant and T variant extends possible variants.
00:19 So you can only pass in, for instance, if we go type example equals modal props, we can only pass in two things, with button or without button. If we just go without, then it's not assignable to the constraint possible variants.
00:33 So we have an is open Boolean on there and we have a variant T variant on there. And then we've got this other very complicated type. We have T variant extends with button.
00:46 If it does extend with button or if it matches with button, then we get button label string on button click this. Otherwise, we get that. So what's happening then is we've got basically a conditional type here. This is what this is, a conditional type. T variant extends with button.
01:04 And if T variant matches with button, then we add the stuff where button is needed. Now modal here, it's not actually sort of being implemented here, but we can see that we have modal is open. And when we have a with button variant, then it's working properly.
01:21 And if we add a without button variant, then it's going to error and it's going to not allow you to pass button label or on button click. So this is all very clever, very clever generic stuff, right? It's sort of understanding the variant that's being passed in and returning different stuff based on that.
01:37 But is there an easier way to handle this? And is there a way that you can refactor this code to make it simpler? And this is stuff that you've seen before. Don't worry, but you're going to just have to navigate around the kind of more complex syntax that's here and pull in something that's simpler, something you've seen before.
01:56 Good luck.