#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 37 of 48medium

What are Exclude and Extract utility types?

Filtering union types.

What You'll Learn

  • Exclude<T, U> utility
  • Extract<T, U> utility
  • Practical applications

Exclude<T, U>

Removes types from a union.

code.tsTypeScript
type AllColors = "red" | "green" | "blue" | "yellow";
type WarmColors = Exclude<AllColors, "blue" | "green">;
// "red" | "yellow"

type Primitive = string | number | boolean | null | undefined;
type NonNullable = Exclude<Primitive, null | undefined>;
// string | number | boolean

Extract<T, U>

Keeps only types that match.

code.tsTypeScript
type AllTypes = string | number | boolean | (() => void);

type Functions = Extract<AllTypes, Function>;
// () => void

type Primitives = Extract<AllTypes, string | number>;
// string | number

Practical Examples

code.tsTypeScript
// Event handling
type AllEvents = "click" | "focus" | "blur" | "keydown" | "keyup";

type MouseEvents = Extract<AllEvents, "click">;
type KeyboardEvents = Extract<AllEvents, `key${string}`>;
// "keydown" | "keyup"

// Remove specific status
type Status = "pending" | "approved" | "rejected" | "cancelled";
type ActiveStatus = Exclude<Status, "cancelled">;
// "pending" | "approved" | "rejected"

How They Work

code.tsTypeScript
// Implementation
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;