DEV Community

Rhenald Karrel
Rhenald Karrel

Posted on

TypeScript Utilities: Pick Utility Example Usage

Let's talk about the Pick utility in TypeScript real quick. What is Pick? Pick is a TypeScript utility that we can use to construct a new Type with a set of properties Keys from an existing Type. That means we can build a new Type by selecting a set of properties Keys (string or union of strings) that exist from another Type to be properties Keys of the new one. Here is the syntax for Pick:

Pick<Type, Keys>

Pick<User, "UserName">

Pick<User, "UserName" | "Email">
Enter fullscreen mode Exit fullscreen mode

Let's see the example. I have a movie app where I can track my movie list/plan to watch. I maybe have the main root Type for the movie which may consist of a bunch of Keys inside the Type. Like "title", "description", "releaseDate", "review", "casts", etc. And when I create a function to get a movie detail, it's clear I need to use the overall Keys to make sure we get the detailed movie data correctly. But, what if I want to create another function where I want to get only the title and current status (watched or not) data of the movie for preview purposes?

interface IMovie {
  title: string;
  description: string;
  releaseDate: string;
  isWatched: boolean;
  ...
}

interface IPreviewMovie {
  title: string;
  isWatched: boolean;
}

export function getDetailedMovieData(): IMovie { }

export function getPreviewMovies(): IPreviewMovie[] { }
Enter fullscreen mode Exit fullscreen mode

In the above example, we declared our interface twice. That's okay for simple usage, but you can imagine when your app becomes more complex and suddenly things begin to be out of control into a Type world of pain. Pick can help us to make our code cleaner and less. Using Pick, we can tell TypeScript to "pick" certain Keys from our existing Type (whether it's an Interface or Type). So, let's refactor it!

interface IMovie {
  title: string;
  description: string;
  releaseDate: string;
  isWatched: boolean;
  ...
}

type PreviewMovie = Pick<IMovie, "title" | "isWatched">

export function getDetailedMovieData(): IMovie { }

export function getPreviewMovies(): PreviewMovie[] { }
Enter fullscreen mode Exit fullscreen mode

See? This allows us to efficiently construct a new Type by using Pick to only use the relevant Keys (ignoring the others). Another thing to remember, be careful not to confuse the "title" | "isWatched" with a Union Type. Pick is a Mapped Type which means that the | syntax is more like an "and" instead of "or". I'll talk more about the Mapped Type later!

Thank you for reading! Hopefully from this small example, you can understand what Pick can do and help you to code cleaner.

Top comments (0)