Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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.
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.
"success" | "error" | "pending", you can extract only "error".Extract<Role, "admin" | "moderator">).Extract helps narrow it to needed values.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
Mixed there are string, number, and boolean.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?
Extract<ApiResponse, { status: "error" }> leaves only those objects with status: "error".This is a more realistic case as handling API responses is a frequent task in frontend development. 🚀
| 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