TypeScript Reference ยท Utility Types
TypeScript Exclude<T, U> utility type
Reference for TypeScript Exclude<T, U>: remove union members that are assignable to U, how distribution works, and common uses with literals and objects.
Exclude<T, U> takes a union type T and removes every member that is assignable to U. What is left is a smaller union. It is built from a distributive conditional type, so it tests each member of T on its own.
Typical uses: dropping a few literals from a union of names, removing null or a function type from a union, or computing the keys of an object except some (that is how Omit works).
type Status = "idle" | "loading" | "error" | "done"; type Active = Exclude<Status, "idle" | "done">; // "loading" | "error"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
type Exclude<T, U> = T extends U ? never : T;
| Name | Description |
|---|---|
T |
The union to filter. Each member is tested separately. |
U |
The type to remove. A member is dropped when it is assignable to U. |
Result: the union of the members of T that are not assignable to U. If nothing remains, the result is never.
Edge cases: Exclude<T, never> is T. Exclude<string, "a"> is still string, because string itself is not assignable to "a"; excluding a literal from a wide type does nothing.
Usage notes
- Works by assignability, not equality.
Exclude<1 | 2 | 3, number>isnever, since all three are assignable tonumber. - Distribution. The conditional type is distributive because
Tis a naked type parameter. A non-unionTis simply tested once. - Not for object properties.
Excluderemoves members of a union. To remove properties of an object type, useOmit<T, K>. - Removing
nullandundefined:Exclude<T, null | undefined>equalsNonNullable<T>for unions. - Opposite:
Extract<T, U>keeps the matching members. - Excluding by discriminant: the object-literal form
Exclude<Shape, { kind: "point" }>works because each member is checked for assignability to that shape. - Available since TypeScript 2.8.