Type Transformations Workshop (9 exercises)

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:

Passing a union into an indexed access type like this will return another union, which is pretty awesome!

Solution 2

Another way to do this is to use Exclude in an indexed access.

This technique creates a union by excluding the members that we don't want, instead of adding the members that we do want:

We can make this a little more readable by extracting the Exclude into a type like so:

And then pass the extracted type into the indexed access like so:

The Exclude technique is a little less typing for us, and the TypeScript compiler does a bit more work.

No matter which way you choose, you end up with the same result as directly passing a union into the indexed access.


[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.