Extract under the hood in TypeScript

Example of Promise.all use
Example of Promise.all use

Today we discuss Type Lookup

This is quite a rare case but if you need to match every element inside a union type by its field type (and you know in advance which one), that's what you need.

Let's take a look 👀

Filterting

This solution looks like what we did in Exclude under the hood:

Exclude solution
Exclude solution

We used Distributive Conditional Types which helped us filtering out the elements we need.

Here, we need to remove not matched (with type) elements of a union. Or in other words (if you don't like double negations as me 😅), we need to pick the union elements of a specific structure. We know in advance that the field is type. Let's try:

Solution, version 1
Solution, version 1

Also, if you're familiar with internal type Extract (it's the opposite what Exclude does), you can apply it here:

Solution, version 2
Solution, version 2

Great job 🔥

Please, don't hesitate to go to the test cases in Playground

Have a wonderful day 🌇

typescript

Alexey Berezin

Senior Software Engineer, UK Global Talent 🇬🇧

The portrait photo of me

Thank you for reading my blog post! If you have any questions, suggestions, or just want to say hi, feel free to reach out in social networks, or via email. I would love to hear from you!

Comments