Understanding some useful TypeScript utility types
In this short guide, we look at four of TypeScript common and helpful utility types: Pick, Omit, Exclude, and Extract.
You can use all of them right away in any TypeScript project as they are built in.
These utilities fall into two groups:
- Pick and Omit work on object types
- Exclude and Extract work on union types
Let's walk through them with simple examples.
Working with objects: Pick and Omit
Imagine you have a big Album type. If you want a version of this type with only some of its properties, you can use Pick.
Pick - "keep only these keys"
type AlbumData = Pick<Album, "title" | "artist">;
This gives you an object type that contains only title and artist. Pick takes the original object type and a union of the keys you want to include.
Omit - "remove these keys"
type AlbumData = Omit<Album, "id" | "releaseYear" | "genre">;
This returns the same object minus those keys. If you remove "genre" from the omit list, then genre appears again. Both Pick and Omit do not change the original type: they simply return a new, transformed type.
Working with unions: Exclude and Extract
If you try to use Extract in place of Pick, TypeScript won't crash, but your type will become never, because Extract is not designed for objects, it only works with unions. Same problem when swapping Omit with Exclude.
Exclude - "remove something from a union"
Suppose you have a union like:
type AlbumState = Released | Recording | Mixing;
If you want everything except Released, you can write:
type NotReleased = Exclude<AlbumState, Released>;
The result is Recording | Mixing. You can also exclude based on a shared shape.
Extract - "keep only the matching parts of a union"
Given a union like:
type Example = "A" | "B" | "C" | 1 | 2;
Using Extract:
type Strings = Extract<Example, string>;
You now get "A" | "B" | "C".
Using Exclude instead:
type Numbers = Exclude<Example, string>;
You get 1 | 2.
Trying to use Pick or Omit on union types won't throw an error, but the results won't make sense as they are not meant for unions.
Conclusion
These four utilities are small but powerful tools for shaping your types. Use Pick and Omit for objects, and Extract and Exclude for unions.