Hack Frontend Community

Utility Type Exclude in TypeScript

Exclude is a utility type in TypeScript that allows excluding specific subtypes from a union type. It creates a new union by removing members that can be assigned to some other type.


Syntax

Exclude<T, U>
  • T — original union type.
  • U — subtypes (or union of subtypes) to remove from T.

Thus, Exclude<T, U> removes from T all subtypes that can be assigned to U, leaving only incompatible ones.


When to use Exclude?

  1. Type cleanup: removing null and undefined to avoid extra checks.
  2. Filtering optional fields: when you need to keep only certain variants in union type.
  3. Working with API data: excluding unwanted values from possible server responses.
  4. Type optimization: reducing number of possible variants for ease of use.

Examples

Example 1. Excluding types from union

type Mixed = string | number | boolean;

// Remove numbers and boolean values
type OnlyStrings = Exclude<Mixed, number | boolean>;
// OnlyStrings = string
  • We have union type Mixed = string | number | boolean.
  • Exclude<Mixed, number | boolean> leaves only those types in Mixed that cannot be assigned to number | boolean.
  • Result is string.

Example 2. Excluding null and undefined

type APIResponse = "success" | "error" | null | undefined;

// Remove null and undefined, leaving only valid statuses
type ValidResponse = Exclude<APIResponse, null | undefined>;

function handleResponse(status: ValidResponse) {
  console.log(`Received response: ${status}`);
}

handleResponse("success"); // ✅ Ok
handleResponse("error"); // ✅ Ok
handleResponse(null); // ❌ Compilation error

  • If we have a type that includes null and undefined, using Exclude we can remove them.
  • Analog of this approach is using NonNullable utility.

Difference from Extract

UtilityDescription
Exclude<T, U>Excludes all subtypes from T compatible with U
Extract<T, U>Leaves only subtypes from T compatible with U
type Mixed = string | number | boolean;
type OnlyNumbersOrBooleans = Extract<Mixed, number | boolean>; 
// number | boolean

type OnlyStrings = Exclude<Mixed, number | boolean>; 
// string

Summary

  • Exclude simplifies managing complex union types, allowing excluding unnecessary variants.
  • Helps "clean" type if you need to work only with specific group of subtypes.
  • Combines with Extract, NonNullable utilities etc. for finer tuning and type filtering.