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!