Unions and Indexing 10 exercises
solution

Extract From A Union Using a Utility Type

The solution here is to use the Extract utility type to extract the click event from the Event discriminated union:


type ClickEvent = Extract<Event, { type: "click" }>

The Extract helper checks if each member of the union extend the type that you pass in, and returns a union of

Loading solution

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.