These utility types, included with TypeScript, are used to obtain a sub-part of a type either through specifying what you're looking for or what you're not looking for.
Behind the scenes they are implemented using conditional types.
Extract
What you're looking for.
Useful for obtaining some sub-part of a type that is assignable to some other type.
type Extract<T, U> = T extends U ? T : never
type FavoriteColors =
| 'dark sienna'
| 'yellow ochre'
| 'sap green'
| 'titanium white'
| 'phthalo green'
| 'prussian blue'
| 'cadium yellow'
| [number, number, number]
| { red: number; green: number; blue: number };
type StringColors = Extract<FavoriteColors, string>;
// type StringColors = "dark sienna" | "yellow ochre" | "sap green" | "titanium white" | "phthalo green" | "prussian blue" | "cadium yellow"
type ObjectColors = Extract<FavoriteColors, { red: number }>;
// type ObjectColors = {
// red: number;
// green: number;
// blue: number;
// }
type TupleColors = Extract<FavoriteColors, [number, number, number]>;
// type TupleColors = [number, number, number]
For type StringColors
you could say:
"We're Extract
ing the subset of FavoriteColors
that is assignable to string
."
NOTE: this is similar to the example of using
keyof
with the&
intersection operator in the Type Queries notes.
Exclude
What you're NOT looking for.
Useful for obtaining some sub-part of a type that is NOT assignable to some other type.
type Exclude<T, U> = T extends U ? never : T
type FavoriteColors =
| 'dark sienna'
| 'yellow ochre'
| 'sap green'
| 'titanium white'
| 'phthalo green'
| 'prussian blue'
| 'cadium yellow'
| [number, number, number]
| { red: number; green: number; blue: number };
type NonStringColors = Exclude<FavoriteColors, string>;
// type NonStringColors =
// | [number, number, number]
// | {
// red: number;
// green: number;
// blue: number;
// }
For type NonStringColors
you could say:
"We're Exclude
ing the subset of FavoriteColors
that is assignable to string
."
From the Intermediate TypeScript↗ course on FEM↗ taught by Mike North↗.