What is the difference between Exclude and Extract in TypeScript?
Both work on union types. Exclude<T, U> removes the members of T that are assignable to U, and Extract<T, U> keeps only those members. They filter a union, not an object's properties; for objects use Omit and Pick.
Explain it simply
Think of a list of payment modes on a checkout page. Exclude is the "remove these" button; Extract is the "keep only these" button. The list in question is a union type, a set of allowed options.
A frequent mix-up: Omit and Pick act on the keys of an object type, while Exclude and Extract act on the members of a union. Omit is actually built from Exclude: it removes keys from keyof T.
Example
type Mode = "upi" | "card" | "cash" | "netbanking";
type Online = Exclude<Mode, "cash">;
// "upi" | "card" | "netbanking"
type OnlyCardOrUpi = Extract<Mode, "card" | "upi">;
// "card" | "upi"
type Id = string | number | boolean;
type Primitive = Extract<Id, string | number>; // string | number
type NotBool = Exclude<Id, boolean>; // string | number
// Object keys: use Omit / Pick
interface User { id: number; name: string; password: string }
type Safe = Omit<User, "password">;What to say in the interview
"Exclude drops union members that match, Extract keeps the ones that match. Both operate on unions. For removing or keeping properties of an object type I use Omit and Pick instead, which are themselves built on Exclude."
Common mistakes
- Passing an object type to Exclude and expecting it to remove a property.