TypeScript Reference ยท Utility Types
TypeScript Extract<T, U> utility type
Reference for TypeScript Extract<T, U>: keep only the union members assignable to U, with literal, object and discriminated-union examples and pitfalls.
Extract<T, U> filters a union T, keeping only the members that are assignable to U. It is the counterpart of Exclude<T, U>: where Exclude throws matches away, Extract keeps them.
Use it to pull the string keys out of a mixed key union, to select the members of a discriminated union by their kind, or to find which members of a union are functions.
type Mixed = string | number | boolean; type Textual = Extract<Mixed, string | number>; // string | number
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type Extract<T, U> = T extends U ? T : never;
| Name | Description |
|---|---|
T |
The union to filter. Each member is tested separately. |
U |
The type to match. A member is kept when it is assignable to U. |
Result: the union of the members of T that are assignable to U. When nothing matches, the result is never.
Edge cases: Extract<string, "a"> is never, because string is not assignable to "a". Extracting from a wide type with a narrow U does not narrow it.
Usage notes
- Assignability, not equality.
Extract<"a" | "b", string>keeps both literals because both are assignable tostring. - Object unions.
Extract<Event, { type: "click" }>keeps the members whosetypeis assignable to"click". This is the usual way to get one case out of a discriminated union without naming it separately. - Distribution. It is distributive, so it acts on each union member; a non-union
Tis checked once. keyofwithstring.keyof Tcan includenumberandsymbol;Extract<keyof T, string>gives only string keys, which is useful before building template literal types.- Result may be
never. Check the result when the filter depends on generics;neversilently makes later code unreachable. - Complement:
Extract<T, U> | Exclude<T, U>isTfor any union. - Available since TypeScript 2.8.