Type Transformations Workshop (9 exercises)
solution

Use Two Operators With Indexed Access to Get All of an Object's Values

The solution is fairly elegant, though it is hard to read when you first take a look at it:

In the above code, we're getting the type of frontendToBackendEnumMap. Then inside of the square brackets, we're saying we want the keys fof frontendToBackendEnumMap.

Cleaning Up the Solution

The above code can be tidied up a bit by creating an intermediate type:

You can see a pattern start to emerge when we lift typeof frontendToBackendEnumMap into the type Obj– We're taking an object, and then we are putting all of the object's keys inside the object.

If we were to manually put the keys inside of Obj, we would get the same result:

But of course, this wouldn't stay up to date with the type itself.

Remember the Obj[keyof Obj] pattern when you need all of the values from within an object.

Transcript

[0:00] The solution is pretty elegant here. It's really quite hard to read when you first take a look at it, so we're getting the typeof frontendToBackendEnumMap here. Then, inside here, we're basically saying get the keys of the frontendToBackendEnumMap.
[0:15] If I tidy this up a little bit and say type Obj, for instance, is typeof frontendToBackendEnumMap and let's just remove these, now you can see this pattern emerge, where we're taking the object and then inside of it we're putting all of the keys of that object.

[0:35] I can achieve the same result by saying multiModule or sharedModule or singleModule. That would get us the same result, except it doesn't stay up to date with the actual type itself.

[0:48] Having Obj keyof Obj is the pattern you need to bear in mind when you want to grab all of the values of an object.