Welcome back! I am Mihir, and in this lesson we will learn Exclude and Extract in TypeScript.
Both utility types work with unions.
Exclude
Exclude<T, U> removes members from union T that are assignable to U.
type Status = "loading" | "success" | "error";
type FinalStatus = Exclude<Status, "loading">;FinalStatus becomes:
"success" | "error"Extract
Extract<T, U> keeps only members from union T that are assignable to U.
type Status = "loading" | "success" | "error";
type ErrorStatus = Extract<Status, "error" | "failed">;ErrorStatus becomes:
"error"Exclude Example
type UserRole = "admin" | "editor" | "viewer" | "guest";
type LoggedInRole = Exclude<UserRole, "guest">;LoggedInRole becomes:
"admin" | "editor" | "viewer"Extract Example
type EventName = "click" | "change" | "submit" | "focus";
type FormEventName = Extract<EventName, "change" | "submit">;FormEventName becomes:
"change" | "submit"Working with Object Unions
type ApiResult =
| { type: "success"; data: string[] }
| { type: "error"; message: string }
| { type: "loading" };
type SuccessResult = Extract<ApiResult, { type: "success" }>;
type NotLoadingResult = Exclude<ApiResult, { type: "loading" }>;These utilities can filter discriminated unions too.
When to Use Them
Use Exclude when you want to remove options.
Use Extract when you want to keep matching options.
They are useful for:
- state unions
- role unions
- event names
- discriminated unions
- helper types
Quick Recap
Exclude<T, U>removes matching union members.Extract<T, U>keeps matching union members.- Both work best with union types.
- They can filter string literal unions and object unions.
- They are opposites in many situations.
Next up, we will learn ReturnType →.