Exclude, Extract and NonNullable

Filtering Union Types

UtilityMeaningExample result
Exclude<U, X>remove members of U assignable to XExclude<"a" | "b" | "c", "a"> = "b" | "c"
Extract<U, X>keep only members of U assignable to XExtract<string | number, number> = number
NonNullable<T>remove null and undefinedNonNullable<string | null> = string

Example

type OrderStatus = "PLACED" | "PACKED" | "SHIPPED" | "DELIVERED" | "CANCELLED" | "RETURNED";

type ActiveStatus = Exclude<OrderStatus, "DELIVERED" | "CANCELLED" | "RETURNED">;
type FinalStatus = Extract<OrderStatus, "DELIVERED" | "CANCELLED" | "RETURNED" | "LOST">;

type Event =
  | { kind: "click"; x: number }
  | { kind: "scroll"; y: number }
  | { kind: "purchase"; amount: number };
type PurchaseEvent = Extract<Event, { kind: "purchase" }>;

type MaybeCoupon = string | null | undefined;
type Coupon = NonNullable<MaybeCoupon>;

const active: ActiveStatus[] = ["PLACED", "PACKED", "SHIPPED"];
const final: FinalStatus = "RETURNED";
const purchase: PurchaseEvent = { kind: "purchase", amount: 999 };
const coupon: Coupon = "FEST20";
console.log(active.length, final, purchase.amount, coupon);

Output

3 RETURNED 999 FEST20

Using an Excluded Member

Example

"DELIVERED" is no longer part of ActiveStatus (TS2322).

type OrderStatus = "PLACED" | "SHIPPED" | "DELIVERED";
type ActiveStatus = Exclude<OrderStatus, "DELIVERED">;
const s: ActiveStatus = "DELIVERED";

Compiler output (tsc)

Line 3: error TS2322: Type '"DELIVERED"' is not assignable to type 'ActiveStatus'.