Codectionary / Developer documentation / TypeScript

Exclude<T> and Extract<T>

Exclude<UnionType, ExcludedMembers> constructs a type by removing specific members from a union. Extract<UnionType, Union> does the opposite, keeping only the members that are assignable to the given type. Both are useful for deriving a narrower union from an existing one without redefining it from scratch.

Syntax

Exclude<UnionType, ExcludedMembers>
Extract<UnionType, Union>

Examples

Exclude<T> - Removing Union Members

Deriving a smaller union by removing specific options.

type Status = "pending" | "active" | "completed" | "cancelled";

type ActiveStatus = Exclude<Status, "cancelled">;
// ActiveStatus is: "pending" | "active" | "completed"

type NonNullableString = Exclude<string | null | undefined, null | undefined>;
// NonNullableString is: string

Extract<T> - Keeping Only Matching Members

The inverse operation - keeping just the members that match.

type AllTypes = string | number | boolean | (() => void);

type OnlyFunctions = Extract<AllTypes, Function>;
// OnlyFunctions is: () => void

type OnlyPrimitives = Extract<AllTypes, string | number | boolean>;
// OnlyPrimitives is: string | number | boolean

Best practices

  • Use Exclude<T> to derive a narrower union type by removing specific known members, keeping it in sync if the original union changes
  • Use Extract<T> when you need to filter a broad union down to just the members matching a certain shape or category
  • Both operate purely on union types - they have no effect on object property removal, which is what Omit is for instead
  • Combine with typeof and a literal array (as const) to derive both a runtime array of values and a matching union type from a single source

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation