Rachelle Rathbone

TypeScript - Extract and Exclude

How to include or omit fields from your types

May 24, 2023

Sometimes you'll come across a type in your codebase that either has part of what you're trying to define or has everything you need along with a bunch of stuff you don't. You may think you have to create a completely new type at this point, but that simply isn't the case. Typescript's built-in Extract and Exclude functionality makes it easy for you to reuse existing types and either build upon them or cut out the fields you don't want to include.

Extract


Extract is the perfect tool when you only want to use part of an existing type.


In the type `BackgroundColors` we're using a mix of strings, an object, and a tuple. To only use part of this type we could do something like:

type StringBackgroundColours = Extract<BackgroundColors, string>;

This type would be defined as:

type StringBackgroundColours = | "lightgrey" | "lightcyan" | "lightgoldenrodyellow";

To extract the tuple we could create the following type:

type TupleBackgroundColours = Extract<BackgroundColors, [number, number, number]>;

Which would be defined as:

type TupleBackgroundColours = [number, number, number];

You may note here this is very specific, constricting us to a tuple of exactly three numbers. But what if you don't care about the length? Well, good news, Typescript allows you to be as specific or general as you want. If, in fact, you wanted an array of any length, you could instead define TupleBackgroundColours as:

type TupleBackgroundColours = number[];

Finally, if we only wanted the object we could create the following type:

type ObjectBackgroundColours = Extract<BackgroundColors, { red: number }>;

Even though we've only included red here, ObjectBackgroundColours would be defined like so:

type ObjectBackgroundColours = { red: number; green: number; blue: number; }

Exclude


Now we know how to create a new type that only includes a small piece of an existing type. But what if we want most of a type and just want to omit one part? That's where Exclude comes into play.

Continuing with BackgroundColors, let's imagine we want to create a new type that includes the object and the tuple but ignores the string values. We can use Exclude to make the following new type:

NonStringBackgroundColoursExclude<BackgroundColors, string>;

Our new NonStringBackgroundColours includes the following properties:

type NonStringBackgroundColours = [number, number, number] | { red: number; green: number; blue: number; }

Hopefully this short post has introduced you to some new Typescript functionality that you can now start to utilise.
...
© 2023, Rachelle Rathbone