Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
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.
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.
null and undefined to avoid extra checks.Example 1. Excluding types from union
type Mixed = string | number | boolean;
// Remove numbers and boolean values
type OnlyStrings = Exclude<Mixed, number | boolean>;
// OnlyStrings = string
Mixed = string | number | boolean.Exclude<Mixed, number | boolean> leaves only those types in Mixed that cannot be assigned to number | boolean.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
null and undefined, using Exclude we can remove them.| 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