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 fromT.
Thus, Exclude<T, U> removes from T all subtypes that can be assigned to U, leaving only incompatible ones.
When to use Exclude?
- Type cleanup: removing
nullandundefinedto avoid extra checks. - Filtering optional fields: when you need to keep only certain variants in union type.
- Working with API data: excluding unwanted values from possible server responses.
- 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 inMixedthat cannot be assigned tonumber | 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
nullandundefined, usingExcludewe can remove them. - Analog of this approach is using NonNullable utility.
Difference from Extract
| Utility | Description |
|---|---|
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.