The Extract
utility type lets us check a union type for a specific members, and returns a new type based on what is left over. It's quite similar in format to the Exclude type.
Let's find out how it works.
Utility Types
Utility Types are types defined in TypeScript to solve particular problems. If you're new to defining custom types in TypeScript, read my guide on defining custom types here.
How the Extract Type works in TypeScript
In TypeScript, we can define a specific type called a union type. A union type is a list of possible values for something. An example is shown below, where the type myUnionType means variables and other outputs can only be one of four values: 🥒, 🥔, 🌶 or 🌽
type myUnionType = "🥒" | "🥔" | "🌶" | "🌽"
// This works since 🥒 is a member of "🥒" | "🥔" | "🌶" | "🌽"
let myFirstVariable:myUnionType = "🥒"
// This doesn't work since "my-string" is NOT member of "🥒" | "🥔" | "🌶" | "🌽"
let mySecondVariable:myUnionType = "my-string"
The Extract Type
If we want to remove specific elements from a union type, we can use the Exclude Type - but there are other ways we can manipulate union types.
The Extract Type lets us define a new list, and returns a new type if any items in that list exist in our original type.
Let's look at a quick example:
type myUnionType = "🥒" | "🥔" | "🌶" | "🌽"
let myFirstVariable:Extract<myUnionType, "🥒" | "🥔"> = "🥒"
// ^
// └ - - Type is "🥒" | "🥔"
When we write Extract, Extract checks myUnionType for "🥒" | "🥔"
. If they exist, it makes a new type containing the items that exist. Since both 🥒 and 🥔 exist in our union type, we end up with a new type - "🥒" | "🥔"
.
If we define members in our Extract
statement which don't exist in our original union type, then they will be ignored in the new type. For example:
type myUnionType = "🥒" | "🥔" | "🌶" | "🌽"
let myFirstVariable:Extract<myUnionType, "🥒" | "🥔" | "🍇"> = "🥒"
// ^
// └ - - Type is STILL "🥒" | "🥔" since "🍇" is not in myUnionType
Using Extract does not affect the original type, so we can still use it if we want:
type myUnionType = "🥒" | "🥔" | "🌶" | "🌽"
let myFirstVariable:Extract<myUnionType, "🥒" | "🥔" | "🍇"> = "🥒"
// ^
// └ - - Type is "🥒" | "🥔"
let mySecondVariable:myUnionType = "🌶"
// ^
// └ - - Type is "🥒" | "🥔" | "🌶" | "🌽"
Extract therefore is a great tool when we want to limit our original union type to a set number of defined members for specific variables or outputs. It gives us flexibility in letting us define types on the fly, which we can use anywhere in our code.
Top comments (2)
Thank you for this! 🙂
No worries!