Skip to content
Tutorials Center
My learning

Topics

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.

TypeScript
type Mixed = string | number | boolean;
type Textual = Extract<Mixed, string | number>;
// string | number

Try it

TypeScript Selecting by kind

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.

TypeScript Keys of a given kind

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

TypeScript
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 to string.
  • Object unions. Extract<Event, { type: "click" }> keeps the members whose type is 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 T is checked once.
  • keyof with string. keyof T can include number and symbol; 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; never silently makes later code unreachable.
  • Complement: Extract<T, U> | Exclude<T, U> is T for any union.
  • Available since TypeScript 2.8.