Type Transformations Workshop (9 exercises)
solution

Simple Syntax Used to Access Parts of a Discriminated Union

As simple as it may seem, here’s the solution:

This works because when you access a key in a union type, you are actually accessing every possible permutation of the union.

Experimenting with the Event Type

For example, let’s remove the type discriminator from "keydown":

Now TypeScript will show us an error at our type EventType = Event["type"]; line because not every branch of the Event union includes a type.

We can put the type back and do a similar experiment where we rename an event:

Now If you try to access "event" from Event and one of the permutations doesn't have it, or is mislabeled, you'll get an error.

It's important to understand you can access parts of discriminated unions, as long as that part belongs to every member of the union.

Transcript

[0:00] Here you go. This is the solution. As simple as it may seem, when you access a key on a union, you're actually accessing all of the possible permutations of that key. It means that EventType ends up being click or focus or keydown.
[0:17] If I were to remove the discriminator here, this would actually not work because it doesn't exist on all of the different branches of the union. It works especially well with discriminated unions because you know in a discriminated union, like type, is always going to be there.

[0:32] Whereas we could do this with the Event, for instance, so Event "event," and we'd end up with MouseEvent or FocusEvent or KeyboardEvent. If one of these was actually mislabeled as mouseEvent, like this for instance, then this wouldn't work.

[0:46] That's a really important thing to understand about these types is that you can actually access pieces of them as long as they belong on each member of the union.