Conditional Types

Extract<T, U>

Constructs a type by extracting from T all union members that are assignable to U.

Definition

TypeScript
type Extract<T, U> = T extends U ? T : never;

Examples

Extracting Specific Members
type Shape = "circle" | "square" | "triangle" | "rectangle";

type Quadrilateral = Extract<Shape, "square" | "rectangle">;
// "square" | "rectangle"

const shape: Quadrilateral = "square";
Extracting Function Types
type Mixed = string | number | (() => void) | ((x: number) => string);

type FunctionsOnly = Extract<Mixed, Function>;
// (() => void) | ((x: number) => string)

const fn: FunctionsOnly = () => console.log("hello");
Narrowing Discriminated Unions
type Action =
  | { type: "fetch"; url: string }
  | { type: "cache"; key: string }
  | { type: "log"; message: string };

type NetworkAction = Extract<Action, { type: "fetch" | "cache" }>;

function handleNetwork(action: NetworkAction) {
  if (action.type === "fetch") {
    console.log("Fetching:", action.url);
  }
}

Common Use Cases

  • 1Selecting specific members from large union types
  • 2Isolating function types from mixed unions
  • 3Creating focused handlers for discriminated union subsets
  • 4Filtering event types for specific subscribers
  • 5Type-safe pattern matching on union categories

Understanding Extract<T, U>

Extract<T, U> is the counterpart to Exclude<T, U>. While Exclude removes union members matching U, Extract keeps only those that match. It is defined as a distributive conditional type: for each member of T, if it extends U, it is kept; otherwise it becomes never.

Extract is particularly useful when working with discriminated unions. If you have a comprehensive Action union type, you can extract specific categories of actions for focused handlers. For example, Extract<Action, { type: "fetch" | "cache" }> gives you only the network-related actions, letting you write a handler that deals exclusively with those.

Another common pattern is extracting function types from a mixed union. When a union contains primitives, objects, and functions, Extract<T, Function> isolates only the callable members. This is useful in meta-programming scenarios where you need to introspect or wrap only the function values.

Extract also enables powerful type-level set operations. You can think of Extract as intersection of unions: the result contains only members present in both T (as a union) and U (as a supertype). This algebraic interpretation makes Extract a building block for more complex type manipulations.

Combined with template literal types, Extract can filter unions of strings by pattern. For example, Extract<EventName, `on${string}`> extracts only event names that start with "on". This kind of pattern matching at the type level is a unique strength of TypeScript's type system.

Related Types

More Conditional Types

Explore TypeScript Types

Browse our complete reference of 30 TypeScript utility types with definitions, examples, and explanations.