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 fromT.
Extract<T, U> keeps in T only those types that can be assigned to U, removing everything else.
When to use Extract
- Extracting valid values: for example, if API can return
"success" | "error" | "pending", you can extract only"error". - Filtering by roles and access: from list of all roles you can extract only administrators (
Extract<Role, "admin" | "moderator">). - Union type optimization: when you need to keep only values of specific type.
- Simplifying work with generics: if large list of variants is passed to template,
Extracthelps 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
Mixedthere arestring,number, andboolean. - Extract leaves only those types that are
numberorboolean.
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?
Extract<ApiResponse, { status: "error" }>leaves only those objects with status: "error".- We use this for error handling, ignoring successful responses and null | undefined.
- 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
| Utility | Description |
|---|---|
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