Exclude, Extract, NonNullable
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;
type NonNullable<T> = T & {};Filter a union by assignability, or remove null and undefined. These are type-level operations; they do not inspect a runtime value.
| Type parameter | Description |
|---|---|
T | Usually a union type to filter. For Extract with a discriminated union, T is the whole union and U is a pattern such as { kind: "ok" }. |
U | The members to drop (Exclude) or keep (Extract). |
Produces: A union of the remaining members, or never if none remain. NonNullable<string | null | undefined> is string.
Type errors
type error— Assigning an excluded member, such as null to Exclude<Status, null | undefined>, is a type error. Extract rejects members that were not kept.
- The signatures are from TypeScript 5.9.3. Exclude and Extract arrived in 2.8. NonNullable was redefined as T & {} in 4.8.
- Extract on a discriminated union is a type-level counterpart to the runtime kind check in the overview result-type recipe. The type still does not throw if a runtime object has the wrong shape.
type Status = "ready" | "pending" | "done" | null | undefined;
type Present = Exclude<Status, null | undefined>;
type Finished = Extract<Status, "ready" | "done" | null>;
type Value = NonNullable<Status>;
const present: Present = "ready";
// @ts-expect-error null was excluded
const absent: Present = null;
const finished: Finished = "done";
// @ts-expect-error pending is not in the extracted union
const pending: Finished = "pending";
const value: Value = "ready";
// @ts-expect-error NonNullable removes null and undefined
const missing: Value = undefined;
type Result =
| { kind: "ok"; value: number }
| { kind: "error"; message: string };
type Ok = Extract<Result, { kind: "ok" }>;
const ok: Ok = { kind: "ok", value: 12 };
console.log(present, finished, value, ok.value);Expected output
ready done ready 12Related: Use a result type for success and failure, Official Exclude, Official Extract, Official NonNullable