TypeScript Exclude Utility Type
`Exclude< T, U >` creates a new union type by removing types assignable to `U` from `T`. It filters out unwanted union members.
Basic Example: Removing Certain Event Types
type AllEvents = "click" | "hover" | "scroll" | "resize";
// Remove 'scroll' and 'resize' events
type UserEvents = Exclude<AllEvents, "scroll" | "resize">;
const event1: UserEvents = "click"; // OK
const event2: UserEvents = "hover"; // OK
// const event3: UserEvents = "scroll"; // Error: Type '"scroll"' is not assignable
Removing `scroll` and `resize` events leaves only user interaction events.
Excluding Nullable Types
type Primitive = string | number | boolean | null | undefined;
// Exclude null and undefined
type NonNullablePrimitive = Exclude<Primitive, null | undefined>;
const value1: NonNullablePrimitive = "hello"; // OK
const value2: NonNullablePrimitive = 42; // OK
// const value3: NonNullablePrimitive = null; // Error
// const value4: NonNullablePrimitive = undefined; // Error
Removing `null` and `undefined` ensures values are always defined and valid.
Usage in State Management
type Status = "success" | "error" | "pending";
// Exclude 'pending' status to create 'final' statuses
type FinalStatus = Exclude<Status, "pending">;
function handleStatus(status: FinalStatus) {
if (status === "success") {
console.log("Operation succeeded");
} else {
console.log("Operation failed");
}
}
handleStatus("success"); // OK
handleStatus("error"); // OK
// handleStatus("pending"); // Error
Excluding `pending` state defines a type with only final results, simplifying function logic.
Why Use Exclude?
`Exclude` helps create precise and controlled types by filtering out unwanted union members.
Back