Unions and Indexing 10 exercises
solution

Extract Specific Members From A Union with Indexed Access

There are a couple ways to solve this.

Solution 1

You can actually pass a union into an indexed access to get the specific members you want:


export type IndividualProgram = typeof programModeEnumMap[
| "ONE_ON_ONE"
| "SELF_DIRECTED"
| "PLANNED_ONE_ON_ONE"
| "PLANNED_SELF_DIRECTED"
]
`

Loading solution

Transcript

0:00 Here's the first solution that you can take for this. We've got a typeof programModeEnumMap. What you'll notice here is that you can pass a union into an index access here. We can say, "ONE_ON_ONE" or "SELF_DIRECTED" or "PLANNED_ONE_ON_ONE" or "PLANNED_SELF_DIRECTED."

0:18 If I comment a couple of these out, what you'll see is we get, "ONE_ON_ONE" or "SELF_DIRECTED" here. Passing a union into an index access type returns another union. Pretty awesome. Very, very useful.

0:33 The other way you can solve this is it's using the same concept, but it uses a little bit of exclude as well. Exclude here, we're using it to take that keyof typeof programMap, "GROUP" or "ANNOUNCEMENT." Then that generates, "ONE_ON_ONE" or "SELF_DIRECTED" or "PLANNED_ONE_ON_ONE," if we see this out.

0:52 We can say, type Example equals this. That's going to grab the pieces that we need and then we can pass them into this, which is nice too. This lets us probably type a little less code to make the typeScript compiler do a bit more work and it means that you end up with basically the same result.