Sub topic 7
Exclude, Extract and NonNullable
This chapter covers the three utility types that filter union types: Exclude, Extract and NonNullable. It assumes you know basic TypeScript syntax, union types, string literal types and generic syntax such as Array<T>. The earlier chapters reshaped object types. These utilities work on the members of a union instead.
Why filter a union?
A union type is a set of alternatives, for example "idle" | "loading" | "error" | "done". You often need a subset of it. A function might accept only the states that are still in progress, or you might want to drop null and undefined after a check.
Without a utility, you would retype the subset by hand. The copy then drifts when someone adds a member to the original union. Filtering utilities derive the subset from the original, so the two stay in sync.
Exclude: remove members
Exclude<T, U> removes from T every union member that is assignable to U.
type Status = "idle" | "loading" | "error" | "done";
type Active = Exclude<Status, "idle">;
// "loading" | "error" | "done"
type Busy = Exclude<Status, "idle" | "done">;
// "loading" | "error"
function describe(status: Active): string {
return `Working on it: ${status}`;
}
describe("loading");
// describe("idle"); // Error: Argument of type '"idle"' is not assignableThe second argument does not have to be a literal. It can be any type, and every member of T assignable to it is removed.
type Mixed = string | number | boolean | null;
type WithoutText = Exclude<Mixed, string>;
// number | boolean | null
type WithoutPrimitives = Exclude<Mixed, string | number | boolean>;
// nullExtract: keep members
Extract<T, U> is the opposite. It keeps only the members of T that are assignable to U.
type Status = "idle" | "loading" | "error" | "done";
type Finished = Extract<Status, "done" | "error">;
// "error" | "done"
type Mixed = string | number | boolean | null;
type OnlyNumbers = Extract<Mixed, number>;
// numberUse Exclude when it is easier to name what you want to remove. Use Extract when it is easier to name what you want to keep.
| Utility | Keeps members that are | Example result for `"a" \ | "b" \ | 1` with `string` |
|---|---|---|---|---|
| `Exclude<T, U>` | not assignable to `U` | `1` | ||
| `Extract<T, U>` | assignable to `U` | `"a" \ | "b"` |
NonNullable: remove null and undefined
NonNullable<T> removes null and undefined from T.
type MaybeName = string | null | undefined;
type Name = NonNullable<MaybeName>; // string
function greet(name: Name): string {
return `Hello, ${name}`;
}
function greetMaybe(name: MaybeName): string {
if (name == null) {
return "Hello, stranger";
}
return greet(name);
}It is useful when a type comes from an optional source, such as an optional property or an array lookup, and you want the type of the value after you have checked it.
interface Config {
port?: number;
}
type Port = NonNullable<Config["port"]>; // numberHere Config["port"] is number | undefined. NonNullable strips the undefined. This uses an indexed access type, which a later chapter covers.
In current TypeScript versions, NonNullable<T> is defined as T & {}. For a union, intersecting with {} drops null and undefined, giving the same result as the older conditional definition in common cases.
How they work: distributive conditional types
Exclude and Extract are conditional types. Their definitions are short:
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;The key behavior is distribution. When T is a bare type parameter and you pass a union, TypeScript applies the condition to each member separately and joins the results. Here is Exclude<"a" | "b" | "c", "a"> step by step:
"a" extends "a" ? never : "a"givesnever."b" extends "a" ? never : "b"gives"b"."c" extends "a" ? never : "c"gives"c".- The union
never | "b" | "c"simplifies to"b" | "c", becauseneveris the empty type and disappears from unions.
This is why never appears in the definitions. Returning never for a member is how a conditional type drops it from the result.
Filtering object unions
The same utilities work on unions of object types. This pairs well with discriminated unions, where each member has a literal kind property.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "triangle"; base: number; height: number };
type Round = Extract<Shape, { kind: "circle" }>;
// { kind: "circle"; radius: number }
type NotCircle = Exclude<Shape, { kind: "circle" }>;
// the square and triangle members
function area(shape: Round): number {
return Math.PI * shape.radius ** 2;
}
console.log(area({ kind: "circle", radius: 2 }));A member is kept by Extract when it is assignable to { kind: "circle" }. The circle member has kind: "circle" and extra properties, and extra properties do not block assignability for types, so it matches. The other members have a different kind and do not match.
This approach lets you name one case of a union without declaring a separate interface for it.
Common errors and edge cases
Excluding a name that is not in the union
Exclude does not check that the second argument is a member of the first. A typo silently removes nothing.
type Status = "idle" | "loading" | "error" | "done";
type Oops = Exclude<Status, "Idle">;
// "idle" | "loading" | "error" | "done" (nothing was removed)If you want the compiler to reject unknown names, write a stricter helper that constrains the second argument.
type StrictExclude<T, U extends T> = Exclude<T, U>;
type Good = StrictExclude<"idle" | "loading", "idle">; // "loading"
// type Bad = StrictExclude<"idle" | "loading", "Idle">; // Error: Type '"Idle"' does not satisfy the constraintConfusing Exclude with Omit
Exclude filters union members. Omit removes properties from an object type. Passing property names to Exclude on an object type does nothing useful.
interface User {
id: number;
name: string;
}
type Wrong = Exclude<User, "id">; // User (User is a single type, not a union of keys)
type Right = Omit<User, "id">; // { name: string }
type KeysOnly = Exclude<keyof User, "id">; // "name"The last line shows a legitimate use: keyof User is a union of key names, so Exclude can filter it. This is exactly how Omit is built.
NonNullable does not change runtime values
NonNullable only changes the type. It does not remove null from anything at runtime. If you write value as NonNullable<typeof value> without checking, you have told the compiler something false.
function first(items: string[]): string {
const item = items[0] as NonNullable<string | undefined>; // unsafe if items is empty
return item;
}Prefer a runtime check, which narrows the type for you:
function firstSafe(items: string[]): string {
const item = items[0];
if (item === undefined) {
throw new Error("The list is empty");
}
return item;
}Whether items[0] is typed as string | undefined depends on the noUncheckedIndexedAccess compiler option. With it off, the type is plain string.
Strict null checks must be on
With strictNullChecks off, null and undefined are assignable to every type. NonNullable then has little to remove. Turn on strict in tsconfig.json so these types behave as shown in this chapter.
Unions of `never`
If every member is removed, the result is never. A function that takes never cannot be called with any value, which usually signals that your filter was too broad.
type Nothing = Exclude<"a" | "b", string>; // neverUsing filters to build a type-safe helper
Here is a short example that combines filtering with a function. It accepts only the states that represent a finished request.
type RequestState = "idle" | "loading" | "error" | "done";
type FinalState = Extract<RequestState, "error" | "done">;
function isFinal(state: RequestState): state is FinalState {
return state === "error" || state === "done";
}
function report(state: RequestState): string {
if (isFinal(state)) {
return `Finished with ${state}`;
}
return `Still going: ${state}`;
}
console.log(report("done"));
console.log(report("loading"));The type predicate state is FinalState narrows state inside the if. In the else path, TypeScript narrows state to Exclude<RequestState, FinalState>, which is "idle" | "loading". The two utilities describe the two sides of one check.
Summary of when to use each
- Use
Exclude<T, U>to drop named members from a union. - Use
Extract<T, U>to keep only members matching a type, including one case of a discriminated union. - Use
NonNullable<T>to removenullandundefined, typically after a check or when reading an optional property type. - Remember that all three are compile-time only, and that
ExcludeandExtractdo not validate their second argument.
Exercise
Given type Event = "click" | "hover" | "keydown" | "keyup";, write one type KeyEvent that keeps only the keyboard events using Extract, and one type PointerEvent2 that removes the keyboard events using Exclude. What are the two resulting types?
Show answer
type KeyEvent = Extract<Event, "keydown" | "keyup">; gives "keydown" | "keyup". type PointerEvent2 = Exclude<Event, "keydown" | "keyup">; gives "click" | "hover". The two results together cover the original union with no overlap.
Exercise
What is the type of Exclude<string | number | null, string | null>, and why? Walk through the distribution.
Show answer
The type is number. string extends string | null is true, so that member becomes never. number extends string | null is false, so number is kept. null extends string | null is true, so that member becomes never. The union never | number | never simplifies to number.