Mapped Types 9 exercises
solution

Map Over the Keys of an Object

The solution to this challenge contains a similar structure to the [R in Route] that we used in the previous challenge:


type AttributeGetters = {
[K in keyof Attributes]: () => Attributes[K]
}

The same general procedure is there as well:

The left side declares what our key is, and

Loading solution

Transcript

0:00 Let's examine this syntax that we have here. This is the solution. If you look at this, it's very, very similar actually to the structure that we saw before here, which is R in Route R. If you think about these little pieces here, they're really still being reflected in the setup here, which is on this side, we declare what the key is. Then we declare what we're going to do with the key.

0:27 Imagine if we strip this out and we just have K here. Now what we end up with is we end up with AttributeGetters K in keyof Attributes. This is really powerful, because what we're saying here is we're taking the keyof Attributes and using it to create a new object. Doing this allows you to create a new object with the pieces of the old object. Extremely useful.

0:54 Here, what we're doing is we're saying, basically, "OK, we've got K and let's just put it in there." We end up with keys and the values being the same, which is the same as the previous exercise. What if we actually want to access the value of that? What if we want to access string, string, and number here?

1:12 Well, we have access to the object and we have access to the key there. All we need to do is say, "Attributes," and then use an index access type and say, "K," here. What we get there is now first name is string, last name is string, and age is a number. This isn't keyof. It's the specific key that we're mapping over. It's first name, last name, or age, depending on where we are in the iteration.

1:41 This is like an iterable basically where we're iterating through something. Now in order to make this pass, all we need to do is structure this so that it becomes a Getter. Now this is a function which returns Attributes K, and we end up with the correct type signature.

1:57 There's a lot going on here but the real key is this idea of K in keyof Attributes. Notice, by the way, that if we were to do this, we actually end up with the same type as in Attributes up here, because we're mapping over it and then extracting the values out of it.

2:12 This can be a useful setup by itself if you want to, for instance, make it undefined or if you want to make it readonly. There's lots of cool tricks here, but this is how you pass this solution.