TypeScript Pick Utility Type

In this article, we'll dive deep into a useful and frequently used utility type - Pick<T, K>.

The Pick utility type, as the name implies, lets you "pick" properties from an existing type and create a new one.

Pick in Action

The basic usage is Pick<T, K> where T is the type from which we're picking, and K is the set of property keys we want to select.

This is easier with an example. Given this User type:

interface User {
  id: number;
  name: string;
  email: string;
  age: number;
}

Now assume we only want to deal with the name and email fields. Here is where Pick makes our life easier:

const pickUser: Pick<User, 'name' | 'email'> = { name: 'Niall Maher', email: 'niall.maher@codu.co' }; 

/* Pick<User,  'name' | 'email'> behaves as if we typed the following (making all the User elements optional):
interface User {
  name: string;
  email: string;
}
*/

In this scenario, pickUser has a new type that only includes the name and email properties from User.

This concept might seem trivial, but when working on large-scale applications with complex data structures, such precise control over your types becomes a game-changer


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

TypeScriptTs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.