How does TypeScript's 'Extract' utility type work, and when would you use it?
TypeScript's Extract
utility type is a powerful built-in type that allows you to extract types from a union that are assignable to a specific type. This utility is particularly useful when you need to filter a union type based on a certain criterion.
Syntax
The Extract
utility type is defined as:
Extract<T, U>
Where T
is the union type from which you want to extract, and U
is the type you want to extract.
Example
Imagine you have a union type of different string literals and you want to extract only certain ones:
type Fruit = 'apple' | 'banana' | 'cherry'; type Citrus = 'lemon' | 'orange'; type ExtractedFruit = Extract<Fruit, 'banana' | 'cherry'>; // ExtractedFruit is 'banana' | 'cherry'
In this example, ExtractedFruit
will only include 'banana'
and 'cherry'
from the Fruit
union type because they were specified in the U
type.
Use Cases
- Filtering types: When you have a complex union type and need to work with only a subset of it.
- Conditional rendering: In a React application where you want to conditionally render components based on the type of data.
- API response handling: When you work with API responses that may return a variety of types, and you need to handle specific cases.
Conclusion
The Extract
utility type is a versatile tool in TypeScript that enhances type safety by allowing you to specifically target and use parts of a union type that meet certain conditions. This can greatly simplify your type management and improve code readability and safety.