TypeScript's Extract Utility Type
The Extract
utility type in TypeScript is used to construct a type by extracting from T
all union members that are assignable to U
. It is particularly useful when you want to filter out specific types from a union type.
Syntax:
type Extract<T, U> = T extends U ? T : never;
Example:
type Fruit = 'apple' | 'banana' | 'orange'; type Citrus = 'orange' | 'lemon'; type Extracted = Extract<Fruit, Citrus>; // 'orange'
In this example, Extracted
will only include 'orange'
because it is the only type common to both Fruit
and Citrus
.
How Does Extract Differ from Exclude?
- Extract: Retains only the types present in both
T
andU
. - Exclude: Removes types from
T
that are present inU
.
Exclude Example:
type NonCitrus = Exclude<Fruit, Citrus>; // 'apple' | 'banana'
In this case, NonCitrus
will include 'apple'
and 'banana'
because they are not present in Citrus
.
When to Use Extract vs. Exclude
- Use Extract when you want to narrow down a union type to only include certain members.
- Use Exclude when you want to filter out certain members from a union type.
Understanding these utility types can help you write more expressive and maintainable TypeScript code, especially when dealing with complex types and type transformations.