Filter Union Types with Extract and Exclude in TypeScript
Learn how to filter union types in TypeScript using Extract and Exclude for safer, more precise types in real-world apps.
Duration
3 min
Access
Free
Transcript
Available
Learn how to filter union types in TypeScript using Extract and Exclude for safer, more precise types in real-world apps.
Duration
3 min
Access
Free
Transcript
Available
Video Transcript
Sometimes you don't need a whole new type. You just want to filter part of an union like this one. TypeScript have utilities that can help you refine union types by including or removing specific members based on condition. Let's see how they work. Let's start with this basic union type.
What if you want to keep only certain members, for example, the ones that represent rounded figures? Let's create a new type named round. We use extract that is part of the TypeScript language. You pass the base type and then what you want to extract. Now, round is just circle.
On the other hand, you can remove or exclude certain things like not round, exclude also part of the language, base type, and then you pass another union about what you want to exclude. In this case, circle. Or if you want to do two things, create a union and now you have only one. This is a simple way to shape types for a specific use case like conditionally filtering valid values. But let's see a real-world example.
Let's create a set of union types for different states. Success! Now let's create another type for errors and another for the loading state. And finally a type for the union of these different states. Let's say you want to create a type only for the completed states.
Let's name it finish it. We use extract and we will extract the types where the property type is success and where the property type is error. So this one and this one. The result of this is an union of a success type and the error type. Now let's do the opposite.
Let's use exclude to create something very similar, not loading, exclude from result where type is loading. That give you success and error. This is common when building state machines, UI loaders or reducers, where you only care about a specific subset of states. Why all of this matters? These tools help you to refine type safety without duplicating logic.
It's especially useful when working with complex units from APIs, UIs, or state models, keeping your code readable and type safe. In summary, use extract to keep only the members that you want described here, or use exclude to remove the members of the base type that match this description.