Hack Frontend Community

Utility Type Extract in TypeScript

Extract is a utility type in TypeScript that extracts from a union type those members that can be assigned to another specified type. Essentially, it creates a new union, leaving only "intersecting" parts.


Syntax

Extract<T, U>
  • T — original union type.
  • U — type (or union) whose members should be kept from T.

Extract<T, U> keeps in T only those types that can be assigned to U, removing everything else.


When to use Extract

  1. Extracting valid values: for example, if API can return "success" | "error" | "pending", you can extract only "error".
  2. Filtering by roles and access: from list of all roles you can extract only administrators (Extract<Role, "admin" | "moderator">).
  3. Union type optimization: when you need to keep only values of specific type.
  4. Simplifying work with generics: if large list of variants is passed to template, Extract helps narrow it to needed values.

Examples

Example 1. Extracting numbers and boolean values

type Mixed = string | number | boolean;

// Extract only numbers and boolean values
type OnlyNumbersOrBooleans = Extract<Mixed, number | boolean>;
// OnlyNumbersOrBooleans = number | boolean
  • In original type Mixed there are string, number, and boolean.
  • Extract leaves only those types that are number or boolean.

Example 2. API example: Filtering errors

type ApiResponse = 
  | { status: "success"; data: string } 
  | { status: "error"; message: string }
  | null
  | undefined;

// Extract only errors
type ErrorResponse = Extract<ApiResponse, { status: "error" }>;

function handleError(response: ApiResponse) {
  if (response && response.status === "error") {
    console.log("Error:", response.message);
  }
}

// Usage:
const res1: ApiResponse = { status: "success", data: "OK" };
const res2: ApiResponse = { status: "error", message: "Request error" };

handleError(res1); // Outputs nothing
handleError(res2); // Output: "Error: Request error"

What's happening here?

  1. Extract<ApiResponse, { status: "error" }> leaves only those objects with status: "error".
  2. We use this for error handling, ignoring successful responses and null | undefined.
  3. Function handleError checks if response is error and outputs message.

This is a more realistic case as handling API responses is a frequent task in frontend development. 🚀


Difference from Exclude

UtilityDescription
Exclude<T, U>Excludes all subtypes from T compatible with U
Extract<T, U>Leaves only subtypes from T compatible with U

Example:

type Mixed = string | number | boolean;

type OnlyStrings = Exclude<Mixed, number | boolean>; 
// string

type OnlyNumbersOrBooleans = Extract<Mixed, number | boolean>;
// number | boolean