# Exclude & Extract

> Filter union types by including or removing specific members.

Subject: TypeScript | Lesson 39 of 54 | 4 min read
Interactive lesson: https://codewithanimation.in/typescript/exclude-and-extract
Previous: [Pick & Omit](https://codewithanimation.in/typescript/pick-and-omit.md) | Next: [Parameters & ReturnType](https://codewithanimation.in/typescript/parameters-and-returntype.md)

## 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"
```

## Common mistake: Exclude vs Omit

The most common mistake in TypeScript is confusing `Exclude` with `Omit`.

`Omit` is for **Objects**: it removes *keys* from an interface or object type.

`Exclude` is for **Unions**: it removes *members* from a union type (like string literals).

## Tip: Under the Hood

These utilities are just conditional types relying on union distribution!

`Exclude<T, U> = T extends U ? never : T`

`Extract<T, U> = T extends U ? T : never`

## Try it: 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.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/exclude-and-extract

## Check yourself

### Question 1

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

- A. It correctly returns 'orange'.
- B. It returns an object type, not a string literal.
- C. TypeScript throws a compile error.

Correct answer: B

Omit is for objects! When you use it on a string union, TypeScript treats the string as a String Object and tries to omit properties from it. You must use Exclude for unions.

- Why not A: Omit is for objects, not unions.
- Why not C: It doesn't throw, it just produces a very strange type.

## 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.
