Utility Types - Exclude and Extract
In this page:
Basic Exclude
Exclude<T, U> removes from the union T every member that is assignable to U, leaving only the members of T that don't match U at all. It's commonly used to trim a small number of unwanted options out of a larger union of literal values.
Example: Basic Exclude
type Role = "admin" | "editor" | "viewer";
type EditableRole = Exclude<Role, "viewer">;
const role: EditableRole = "editor";
console.log(role);
Basic Extract
Extract<T, U> does the opposite of Exclude — it keeps only the members of union T that are assignable to U, discarding everything else. Together, Exclude and Extract cover both directions of filtering a union based on another type.
Example: Basic Extract
type Role = "admin" | "editor" | "viewer";
type ElevatedRole = Extract<Role, "admin" | "editor">;
const role: ElevatedRole = "admin";
console.log(role);
Exclude with Literal Unions
Exclude is useful for creating a smaller set of allowed literal values by removing specific options from a larger union of string or number literals, such as removing a deprecated status value from a Status union.
Example: Exclude with Literal Unions
type Status = "active" | "inactive" | "deprecated";
type CurrentStatus = Exclude<Status, "deprecated">;
const s: CurrentStatus = "active";
console.log(s);
Extract with Object Unions
Extract can select members from a union based on a shared structural property, which is useful when the union contains several object shapes and you only want the ones matching a particular pattern.
Example: Extract with Object Unions
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "line" };
type Filled = Extract<Shape, { kind: "circle" } | { kind: "square" }>;
const f: Filled = { kind: "circle", radius: 3 };
console.log(f);
Choosing Exclude or Extract
Use Exclude when you want to remove specific union members from a larger set, and Extract when you want to keep only the members matching a particular type — the two utilities are natural complements.
Example: Choosing Exclude or Extract
type Status = "active" | "inactive" | "banned";
type Removed = Exclude<Status, "active" | "inactive">;
type Kept = Extract<Status, "active" | "inactive">;
const removed: Removed = "banned";
const kept: Kept = "active";
console.log(removed, kept);
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- TypeScript Advanced Types
- Mapped Types
- Conditional Types
- Custom Type Guards
- Assertion Functions
- Control Flow Analysis
- Exhaustiveness Checking
- Satisfies Operator
- Template Literal Types
- Utility Types - Partial
- Utility Types - Required
- Utility Types - Readonly
- Utility Types - Pick
- Utility Types - Omit
- Utility Types - Record
- Utility Types - Exclude and Extract
- Utility Types - NonNullable
- Utility Types - ReturnType
- Utility Types - Parameters
- TypeScript 5 Updates