Part of Series: TypeScript Utility Types
Typescript

How the TypeScript Extract Type Works

📣 Sponsor

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 ExtractType

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.

Last Updated 1649421271311

More Tips and Tricks for Typescript

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email