TypeScript Extract Utility Type

In this article, let's learn about the Extract utility type - Extract<Type, Union>.

Extract<Type, Union> is a utility type that creates a new type by filtering out the types with the given Union.

This utility becomes extremely useful once you know how to use it.

Let's See It in Action

Show me the code!

I think it'll make more sense when you see it in action:

type Food = "apple" | "broccoli" | "banana";
type Fruit = Extract<Food, "apple" | "banana">;
// Fruit is "apple" | "banana"

In this simple example, you see where we can pull types based on the union, but that's not exciting.

Where it gets exciting is when you have more complex types:

type Posts =
  | { type: "article"; title: string; body: string }
  | { type: "video"; title: string; url: string }
  | { type: "image"; title: string; url: string };

type HasUrl = Extract<Posts, { url: string }>;

/* type HasUrl = {
    type: "video";
    title: string;
    url: string;
} | {
    type: "image";
    title: string;
    url: string;
} */

In this second example, you can see how this could be very useful in sieving out the correct types to add even more type safety in certain situations.

Happy coding! 🍕


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

TsTypeScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.