Using Generics with Components 11 exercises
solution

Use the Angle Brackets Syntax to Pass a type to a Component

Before we get to the solution, let's look at an example for test purposes only– this is not something you should do in real life!

Here we create a new variable result by calling Table like a function:


const result = Table({
rows: [
{
id: "123",
},
],
renderRow

Loading solution

Transcript

00:00 This is a cool solution. The way this works is in a normal function, let's say we were going like a const result equals table. Let's actually call it like a function. This is something you should never do, but I'm going to do it for just test purposes to show how it works. So table here.

00:17 Now table, we can pass in rows and we can pass in like, let's go ID for now and just have this render row function which just returns and I'll just grab this row just to make sure we're getting the inference. Now, when we call it like a function, what we can see is we can actually see the inference site here.

00:37 So ID string. Very nice. But how would we manually pass in a type to make sure that rows was what we wanted it to be? Well, we've got this option here where we can actually pass in user, and now this user, this is going to error just here.

00:56 Type string is not assignable to type number. So if we pass in actually 1, 2, 3, then we need to pass in 24 and name Sophia or something. Then you can see that this rows is actually being typed from this type annotation here.

01:14 So this type annotation here works in functions, but does it also work in components? Yes, it does. Where do we put it though? Do we put it here? Is that going to work? No, that looks crazy. Do we put it here? No, that doesn't work. Turns out the slot that they decided to put this in

01:32 was just after the JSX element itself. So this tag here, we can put user like that. Doesn't that look crazy? So now it's expecting 1, 2, 3 here to be a user. If we hover over this error type number is not assignable to type user, and this row here is typed as user2.

01:52 Let's do the same thing here. Whoops, no, not you. User, bam. And suddenly, this is erroring because string is not assignable to type number. So just like a function where you can pass in types to override the inference that's happening, you can do the same thing with components.

02:11 What a crazy piece of syntax. It's pretty amazing that they actually thought of this and decided to implement it. I love it.