Exclude & Extract
Filter union types by including or removing specific members.
Filtering Unions
Exclude<UnionType, ExcludedMembers> creates a new type by removing specific members from a union.
Extract<UnionType, IncludedMembers> does the opposite: it creates a new type by keeping *only* the members that exist in both unions (an intersection).
State Machines
When working with complex state machines or discriminated unions, you often need subsets of states.
If you have type Status = "idle" | "loading" | "success" | "error", and you need a type just for the finished states, you can use Extract<Status, "success" | "error"> rather than duplicating the strings.
Syntax
typescript
type Status = "idle" | "loading" | "success" | "error";
// 1. Exclude (remove members)
type PendingState = Exclude<Status, "success" | "error">;
// "idle" | "loading"
// 2. Extract (keep members)
type FinalState = Extract<Status, "success" | "error" | "aborted">;
// "success" | "error"
Try it
Toggle members from a base union type. Switch between Exclude and Extract to see how the conditional type logic filters the final union.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
Excluderemoves members from a union.Extractkeeps only the specified members in a union.- Use
Excludefor union types, useOmitfor object types. - Both are implemented using conditional types and the
nevertype.
Done with this concept?
Mark it complete to track your progress. No login needed.