Hooks 11 exercises
solution

Fix useState's never[] Error

In this lesson, we will work on customizing the type inference for useState.

Instead of inferring the never array, we need to customize what useState is inferring.

Quickly Fixing the Error

As a quick way to fix the error, we can pass an object with an id and value into useState:

`

Loading solution

Transcript

0:00 The thing we need to do to make this work is make useState, instead of inferring never array, we need to customize what it's inferring. Obviously, the first way we could do that, we could just pass in id 1 and then value Matt here, for instance.

0:16 This would actually work great. We're now getting all of our errors go away. setTags is working perfectly. As you can see, the thing that gets inferred in here instead of never array, it's actually an array of id number value string.

0:30 This is pretty ugly to look at. I wonder if there's a better way to do this. It actually breaks our requirements because we want to start this component with an empty array. How do we make useState understand that it's supposed to be that type?

0:44 You see that when we hover over useState here, there's useState. Then there's open brackets and then the type and then close brackets here. I wonder what would happen if we actually just use that syntax ourselves.

0:57 Let's say that we use this type here. We open up an object. Now that object, let's say we call it an array. We add id number and then value string here. Now this seems to work. Now tag is now typed properly, id number value string. We're getting the inference on id, inference on value. setTags is working beautifully.

1:24 This is a little bit ugly though. When we hover over this, we're getting this crazy type thing here. Wouldn't it be better if we actually just extracted this out into a type of Tag?

1:34 Now type of Tag, we're going to grab those two things, stick them in there. We're going to use Tag array here. This means now that when we hover over it, we're getting this beautiful Tag type there. We still get the nice inference here, so Tag, tag.id. Ooh. It all seems to be working.

1:52 There we go. When you have a type that you need useState to infer, you can actually pass it as a type argument, meaning that you can get around these annoying TypeScript errors where never is going to be creeping in.

2:05 This is a pretty crucial way to use useState. Pretty much every time I declare a useState, I always pass it a type argument. In the next exercise, I'm going to show you another example of that.