Four Approaches to Typing Props
There are four main ways to solve this challenge.
Use an Interface to Type Props
With an interface, we are basically saying that the props correspond to this interface.
className as a string in the interface, the parent component now has to expect a
0:00 There are four main ways to achieve this. When we have an interface here, we're saying, "OK, these Props correspond to this interface," which means that we have className: string here.
0:12 This Parent now, it has to expect a className: string. You can see that when you autocomplete here that we get className as one of the attributes that's coming up. An interface there is perfectly fine.
0:23 The other way to do it is with a type. Type versus interface doesn't really matter. We can express object, which is what props are, through types or interfaces. Again, we've just got type Props up here. I would probably call this ButtonProps or something similar and I would export it.
0:40 It doesn't matter which one you use out of type or interface, but what we're doing here is we're extracting these types outside of the function definition. When we export them as well, we can potentially use them in different places throughout our application, if we need to extend them or compose them or something.
0:56 The next thing you can do is you can define your types in line here. This makes no difference with the other two approaches, but now we're not having to define an extra type, and we just plonk them in there. This is what I find in most code bases, this approach.
1:10 What's even more common is this approach, which looks semantically pretty confusing. Where on the left-side of this colon here, we have some destructuring. These are the props here. This is like doing const = props, like this and having your className in the middle there. What they're doing here is they're destructuring right at the point where they're instantiated.
1:36 On the right-hand side, you've then got the inline definition. What we could do here is we could extract this out, type Props = this and have this there. Honestly, this is what I see in most code bases these days. It's this pretty thrown together definitions like this. These are perfectly fine. There's nothing wrong with this.
1:55 This might end up being a little bit tricky when you try to extract out the props later and you might regret not having it in an external type like this. Then, again, you might not. To be honest, if you're not planning to compose together your prop types or anything like that this is perfectly fine. As you can see, all of these four solutions pass our tests.