Exclude & Extract

Filter union types by including or removing specific members.

TypeScript4 min readConcept 39 of 54

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.

Filter Subset
// 1. The Base Union
type Status ="idle"|"loading"|"success"|"error";

// 2. The Filtered Type
type Filtered =Exclude<Status,"success" | "error">;
Derived Union
"idle"
|"loading"
T extends U ? never : T

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1If `type Fruit = 'apple' | 'banana' | 'orange'`, what happens if you write `type Citrus = Omit<Fruit, 'apple' | 'banana'>`?

Remember this

  • Exclude removes members from a union.
  • Extract keeps only the specified members in a union.
  • Use Exclude for union types, use Omit for object types.
  • Both are implemented using conditional types and the never type.

Done with this concept?

Mark it complete to track your progress. No login needed.