Skip to content
jshacks.dev
TypeScript

The Exclude Utility Type in TypeScript, With Examples

Exclude removes members from a union type. See how the conditional type works, why it distributes, where it cannot subtract and how it differs from Omit.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, JavaScript and Node.js logos.

Exclude<T, U> takes a union type T and removes every member that is assignable to U. It is the utility for narrowing a set of allowed values: all statuses except the ones a function does not handle, all keys of an object except id, a type with null and undefined taken out. It works on unions, not on object types, and that distinction is the first thing to get right, because Omit is the utility for removing properties. This post explains the definition, the distribution rule that makes it work, the cases where it cannot subtract, and the patterns that use it in real code. It uses TypeScript 6.x, and the reference is the Exclude entry in the utility types page.

The basic idea

Pass a union and the members you want gone.

basic.tsTypeScript
type Status = "draft" | "review" | "published" | "archived";

type Live = Exclude<Status, "draft" | "archived">;

const s: Live = "review";

console.log(s);
Text
review

Live is "review" | "published". The second argument can itself be a union, and any member of T that is assignable to any member of U is removed. A single literal also works: Exclude<Status, "draft">.

How it is defined

Exclude is a conditional type with one branch that returns never.

my-exclude.tsTypeScript
type MyExclude<T, U> = T extends U ? never : T;

type Rest = MyExclude<"a" | "b" | "c", "a">;

const values: Rest[] = ["b", "c"];

console.log(values);
Text
[ 'b', 'c' ]

The definition reads: if T is assignable to U, produce never, otherwise keep T. The result for a union is not computed for the union as a whole, but for each member separately, and the pieces are joined. A union with never as a member is the same as the union without it, so the removed members disappear. This is the behavior called distribution, and the conditional types page of the handbook documents it.

Why it distributes

Distribution happens when the checked type is a naked type parameter, meaning T on its own and not wrapped in anything. TypeScript then splits a union argument into its members, evaluates the conditional for each, and unions the results. For MyExclude<"a" | "b" | "c", "a"> that is three evaluations: "a" gives never, "b" gives "b", and "c" gives "c".

You can see what the distribution buys by switching it off. Wrapping both sides in a tuple makes the check apply to the union as a whole.

no-distribution.tsTypeScript
type NotDistributive<T, U> = [T] extends [U] ? never : T;

type R = NotDistributive<"a" | "b", "a">;

const r: R = "a";

console.log(r);
Text
a

The pair ["a" | "b"] is not assignable to ["a"], so the condition is false and the whole of T is returned. Nothing was removed, and "a" is still allowed. This is occasionally what you want in a different utility, but for Exclude the distribution is the entire point.

What the compiler enforces

The result is an ordinary type, so the usual assignability errors apply. A function parameter makes a clear example.

param.tsTypeScript
function double(n: Exclude<string | number, string>): number {
  return n * 2;
}

double("4");
Text
param.ts(5,8): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Exclude<string | number, string> evaluates to number, so the parameter rejects the string and the error names number. Inside the function body, the benefit is just as concrete: n * 2 compiles because n can no longer be a string.

Excluding from unions of objects

Exclude works on any union members, including object types. A member is removed when it is assignable to the excluded type, and an object with a literal type field is assignable to a pattern that lists the same literal.

events.tsTypeScript
type AppEvent =
  | { type: "click"; x: number }
  | { type: "key"; key: string }
  | { type: "scroll"; dy: number };

type Discrete = Exclude<AppEvent, { type: "scroll" }>;

function describe(e: Discrete): string {
  switch (e.type) {
    case "click":
      return `click ${e.x}`;
    case "key":
      return `key ${e.key}`;
  }
}

console.log(describe({ type: "key", key: "a" }));
Text
key a

The scroll member is gone, so the switch needs only two cases, and the compiler agrees that every path returns a string. If someone later adds a fourth event, Discrete includes it and the function stops compiling until the new case is written. That is the same exhaustiveness guarantee that discriminated unions give, with the extra property that the exclusion is stated once, at the type.

Excluding keys

The most common use of Exclude outside plain unions is on keyof, because a key union is a union of string literals. Combine it with a mapped type to build an object type without some keys.

keys.tsTypeScript
interface Product {
  id: number;
  name: string;
  price: number;
}

type Editable = {
  [K in Exclude<keyof Product, "id">]: Product[K];
};

const e: Editable = { name: "Pen", price: 2 };

console.log(e);
Text
{ name: 'Pen', price: 2 }

This is the definition of Omit with the Pick step written by hand. If you only need the result, use Omit<Product, "id">. The hand written form is useful when you want to change the values at the same time, for example to make each remaining property a function, because the mapped type gives you the key name in K.

Cases where Exclude cannot subtract

Exclude removes union members. It does not carve a value out of a wider type, because a wide type is one member.

wide.tsTypeScript
type Wide = Exclude<string, "a">;

const w: Wide = "a";

console.log(w);
Text
a

string is assignable to "a"? No, the other way round: "a" is assignable to string. The condition string extends "a" is false, so string is kept whole, and "a" is still a valid value. TypeScript has no negated types, so there is no way to say "any string except a". If you need that, validate at runtime and use a branded type.

The opposite surprise is boolean, which is a union of true and false internally and therefore can be split.

boolean.tsTypeScript
const f: Exclude<boolean, true> = false;

console.log(f);
Text
false

Enums behave the same way. A union enum is a union of its member types, so Exclude<Color, Color.Red> leaves the other members. This works for string enums and for numeric enums where every member is a literal.

Practical patterns

The first pattern is removing undefined inside a generic function. When you filter an array, the element type still includes undefined unless a type predicate says otherwise, and Exclude expresses the narrowed type.

defined.tsTypeScript
function defined<T>(items: (T | undefined)[]): Exclude<T, undefined>[] {
  return items.filter((item): item is Exclude<T, undefined> => item !== undefined);
}

console.log(defined([1, undefined, 2]));
Text
[ 1, 2 ]

For T = number the return type is number[]. The type predicate is the part that makes the compiler accept the claim, and it is your responsibility to keep it true, because the compiler trusts it. For the specific case of null and undefined, the dedicated NonNullable utility is shorter.

The second pattern is handler tables. A map from event name to handler needs an entry for every event except those handled elsewhere, and Record<Exclude<EventName, "internal">, Handler> states that without repeating the list. The third pattern is function overloads and conditional return types, where Exclude strips a member from a generic parameter inside another conditional type. It is rarely the first tool to reach for there, but it keeps such types short.

Exclude, Extract and Omit

Three utilities are easy to confuse, and each answers a different question.

  • Exclude<T, U> keeps the members of a union that are not assignable to U.

  • Extract<T, U> keeps the members that are assignable to U. It is the exact complement.

  • Omit<T, K> removes properties from one object type, and it is built on Exclude.

If the thing in your hand is a union of string literals, object types or primitives, you want Exclude or Extract. If it is one object with many properties, you want Omit or Pick. Mixing them up produces confusing results: Exclude<User, "email"> does nothing, because User is one member and is not assignable to "email".

When not to use Exclude

Do not use it to model a rule such as "any number except zero", which no static type can express. Do not use it on a wide type like string and expect values to be rejected, as the example above shows. If you need to list the remaining members for readability, write the union out and name it, because Exclude<Status, "draft" | "archived"> is shorter but reads worse than "review" | "published" when the union has three members. And when the excluded set is the large part, prefer Extract, since describing what you keep is clearer than describing what you remove.

Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.