
TypeScript Guide 05: Unions, Exclude and Extract
Video
Watch the full video on YouTube:
Exclude: Excluding Elements
Exclude allows us to create a new type by excluding elements from a union:
type CountryISOCode = "VE" | "CO" | "CL" | "UY" | "CA" | "USA"
type LatinAmericanCountryISOCode = Exclude<CountryISOCode, "CA" | "USA">
// Result: "VE" | "CO" | "CL" | "UY"
Exclude with Complex Objects
Exclude works very well with complex objects:
type PaymentMethod =
| { name: "PayPal"; config: { apiKey: string } }
| { name: "Stripe"; config: { publishableKey: string } }
| { name: "Binance"; config: { apiKey: string } }
type AvailablePaymentMethods = Exclude<PaymentMethod, { name: "PayPal" }>
// Result: Stripe and Binance
Filtering by Nested Properties
We can filter by nested properties:
type PaymentMethodsWithStringKey = Exclude<
PaymentMethod,
{ config: { publishableKey: string } }
>
// Result: Only Binance
Extract: Extracting Elements
Extract is the opposite of Exclude, it allows us to extract specific elements:
type NonLatinAmericanCountryISOCode = Extract<CountryISOCode, "CA" | "USA">
// Result: "CA" | "USA"
Extract with Complex Objects
Extract shines with complex objects:
type AvailablePaymentMethodsWithStringKey = Extract<
PaymentMethod,
{ config: { publishableKey: string } }
>
// Result: Stripe and RevenueCAT
Exclude vs Pick
- Exclude: Works with unions and excludes elements
- Pick: Works with objects and selects properties
// Exclude with unions
type A = Exclude<"a" | "b" | "c", "a"> // "b" | "c"
// Pick with objects
type B = Pick<{ a: string; b: number; c: boolean }, "a" | "b">
// Result: { a: string; b: number }
Extract vs Omit
- Extract: Extracts elements from a union
- Omit: Excludes properties from an object
// Extract with unions
type A = Extract<"a" | "b" | "c", "a" | "b"> // "a" | "b"
// Omit with objects
type B = Omit<{ a: string; b: number; c: boolean }, "c">
// Result: { a: string; b: number }
Use Cases
Filter Payment Methods
type ActivePaymentMethods = Exclude<PaymentMethod, { name: "PayPal" }>
Extract Only Methods with String Config
type PaymentMethodsWithStringConfig = Extract<
PaymentMethod,
{ config: { apiKey: string } } | { config: { publishableKey: string } }
>
// Result: PayPal, Stripe and Binance
Exclude Multiple Elements
type AvailableCountries = Exclude<CountryISOCode, "CA" | "USA" | "VE">
// Result: "CO" | "CL" | "UY"
Extract by Value Type
type StringOrNumber = string | number | boolean | null
type OnlyStringOrNumber = Extract<StringOrNumber, string | number>
// Result: string | number
Conclusion
Exclude and Extract are powerful tools for manipulating type unions. Exclude allows us to exclude elements, while Extract allows us to extract specific elements. Both are fundamental for creating derived types in a clean and maintainable way.
