Type Transformations Workshop (9 exercises)
Problem

Extracting Members of a Discriminated Union

Here we have a discriminated union called Event which has a discriminator called type on it:

Challenge

Your goal for this challenge is to extract the "click" type into a new type called ClickEvent.

As seen earlier, this could be done manually:

But instead you should extract this type directly from the Event discriminated union, without double declaring the type.

Reference the TypeScript Docs to find a utility type that will help you extract a specific type from a discriminated union.

Transcript

[0:00] Here we are extracting the event from this event type here. What you'll notice is that Extract, which is a new type helper, we've not seen this one before, it grabs all of the pieces it needs. What it's doing here is it's checking if any of these conform to this little type. They were checking if they extend that type. If they do, then extract the entire thing.
[0:27] Like we could do this in a different way, where we could say, event is MouseEvent here, and it would still work, because event, it's another differentiator here. If we added a different thing here in said, a: string for instance, then we would try to grab the one that has a: string on it like this.

[0:46] If another one of these events would have a string on it here, then we would end up with a union of both of those things. Extract is super useful. It doesn't even need to be done on objects. It will be done on any union.

[0:59] If we wanted to let's say, we have some fruits type here, apple, orange or banana. We just wanted to extract, let's say, the banana and orange from this. Then we would say, BananaAndOrange equals, can spell, Extract, fruits. Then we would say, banana -- in fact we can just grab a banana from there -- or orange like this.

[1:26] Now, this looks a little bit strange, because we're having to double declare it here, but what we'll see later is we can use Extract and its other half as well to do some really, really cool things with managing Union types. That's how they work.