← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 16 of 20

Utility Types - Exclude and Extract

Exclude<T, U> removes from T the union members assignable to U. Extract<T, U> does the opposite by keeping only members assignable to U.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.