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: stringExtract<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 | booleanBest 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
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook