Unions and Indexing 10 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:


type BackendModuleEnum =
typeof frontendToBackendEnumMap[keyof typeof frontendToBackendEnumMap]

In the above code, we're getting the type of frontendToBackendEnumMap. Then inside of the squar

Loading solution

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.