Essential Types And Notations 20 exercises
solution

Adding Types to Maps

There are a few different ways to solve this problem, but we'll start with the most straightforward one.

The first thing to do is to create a User type:


type User = {
name: string;
age: number;
};

Following the patterns we've seen so far, it shouldn't take too much guesswork

Loading solution

Transcript

00:00 I've added a few different solutions here, but there's one main one you need to get. You can see I've added a type user at the top here, just for convenience for later. And this map now, we can see that it's got an any, any on it. And by a little bit of guesswork, we can see that if we pass in number and user, it will

00:19 start to go away. You can see a little bit of autocomplete there. If we hover over number here, or actually while we're typing, number, user, yeah, you can see that there's a K and a V in those little slots here. And those K and V, that represents key and value.

00:36 So map now, we can go for number and user, and now it starts working. So we can no longer pass in, you know, ABC into this set function here. And also when we get stuff from it, so let's say const results equals user map dot get, we have to pass in a number, as you can see from this overlay.

00:55 So one, and we get back user or undefined. If we didn't do this, then it would actually be typed as something different here. So yeah, it wouldn't be typed as user. So that's the first method we've also got. Of course, we can do this inline as well. We don't have to declare the user object outside. Or we could do it in the method that we discussed before.

01:15 So we could say user map is a map, and then we don't need to pass in any keys or any type arguments rather, to this new map up the top here. So that's another way of doing it. Or, of course, we could just, I've given you all the possible solutions here. That's very nice of me, isn't it?

01:32 So we've got map, number, and user as a variable annotation there. And we've extracted the type outside it. So again, just passing type arguments to functions is just so, so useful. And it comes up a lot more than you think.