Select a discriminated-union variant
A union represents multiple object variants and a function needs one specific discriminant.
TypeScript · Type Alias
Extract filters a union by retaining the members of Type that are assignable to Union. It is a globally available built-in utility type for selecting compatible variants or types.
Extract is a built-in conditional utility type that filters a union. It produces a new type containing the members of Type assignable to Union, which is useful for selecting specific variants from broad unions.
Extract<Type, Union>| Name | Type | Description |
|---|---|---|
Type | type | The source type whose union members are tested. |
Union | type | The type that retained members must be assignable to. |
A type containing the members of Type that are assignable to Union.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; sideLength: number };
type Circles = Extract<Shape, { kind: "circle" }>;
const circle: Circles = { kind: "circle", radius: 10 };Extract keeps only the Shape union member whose kind is "circle".
A union represents multiple object variants and a function needs one specific discriminant.
A broad union mixes primitives and callable values.
A generic API needs to narrow a union according to a caller-provided constraint.
Extract<Type, Union> returns the subset of Type's union members that are assignable to Union. For example, Extract<"a" | "b" | "c", "a" | "f"> evaluates to "a".
Follow-up: How can you select one variant of a discriminated union? Use an object pattern such as Extract<Shape, { kind: "circle" }> so only the compatible member remains.
It is available globally as a utility type and operates on union members. It does not create a runtime value or perform runtime filtering.
Follow-up: What happens when Type is not a union? The same assignability test is applied to that type, producing it when compatible or never otherwise.
Extract was released in TypeScript 2.8. Its declaration has two type parameters: the source Type and the target Union used for the assignability check.
Follow-up: How does it differ from Exclude? Extract keeps members assignable to the second type, whereas Exclude removes those members.
ExcludeNonNullableReturnTypeInstanceType