TypeScriptUtility types
Extract<Type, Union>
Keeps in a union only the types that match a given type.
Example
#TypeScript
type Action =
| { type: 'add'; title: string }
| { type: 'remove'; id: number }
| { type: 'clear' }
type AddAction = Extract<Action, { type: 'add' }>
// type AddAction = { type: 'add'; title: string }
const action: AddAction = { type: 'add', title: 'New task' }
console.log(action.title)Result
New task
Definition and usage
#Extract<Type, Union> does the opposite of Exclude: it keeps only the union members that match the second argument.
It’s especially useful with discriminated unions. Extract<Action, { type: "add" }> pulls out of the action union exactly the variant with type: "add", along with all of its fields.
Just like Exclude, it’s built on a conditional type that returns never for members that don’t match.
Syntax
#Syntax
type New = Extract<Union, Condition>Type parameters
#Type
union
The union you are selecting types from.Union
type
The type the kept members must match.
Good practices
#- With discriminated unions,
Extractis the most convenient way to name a single variant. - If the result is
never, no union member matches the condition. Check the spelling of the literals.
Related entries
#Spotted a mistake or missing an example? Write to us.