Skip to main content
Practice Problems

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

ts
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

ts
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

ts
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:

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

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems