DEV Community

Leonardo Oliveira
Leonardo Oliveira

Posted on

001 - TSExpert | Pick Typescript ๐Ÿ”ฅ

Hello folks! ๐Ÿ‘‹๐Ÿผ

Once again, we're here, and today we're diving into the world of a TypeScript built-in utilityโ€”specifically, the Pick utility.

It comes pre-installed with TypeScript and is a handy tool for our daily tasks. But... what exactly is it designed for, and how does it help us?

This utility type has a semantic name because it literally picks certain types for us, provided by a primary type. I'll demonstrate it for you.

Let's suppose we have a blog application, and we create a type definition called User, as follows:

Image description

It works very well, but... now we need to implement a header with a small section that must have the name of the user and their email.

We've created the component, and let's declare the component's props. The most common approach is to create a new type for this component, but now the Pick utility shines bright!

Instead of creating a new type, we can just 'pick' some information from that User type. Let's see how:

Image description

That's it. Our new type called HeaderProps inherits the name and email props from the User type.

Don't believe me? Okay, I'll prove to you that using Pick is the same thing as if we created this new type by declaring it from scratch.

If we hover the mouse over the HeaderProps declaration, TypeScript shows us the format of this type, and voila, it looks exactly how we wanted!

Image description

It's really easy to use, and it's helpful.

โš ๏ธ BUT NOW, I NEED TO ASK YOU A QUESTION! โš ๏ธ

Do we really understand how the Pick utility works and how it performs this 'magic'?

As our friend Richard Feynman says:

"What I cannot create, I do not understand."

For this question, the best answer is to apply all of these principles by working on a new type, our utility-type called Just it'll be the same thing that Pick built-in utility.

The act of creating a new type with the same behaviors as the built-in utility just puts our concepts and knowledge about this utility to the test.

In summary, we need to receive a first type and the respective props that we want to keep. Let's get started.

After spending much time working on it...

Image description

Here's our own implementation of the Pick utility.

You can see that I've given some semantic names to my props. Let's check out each of them.

First, I created a type called Just, which receives two generics. The first will be the Primary type, the type from which we will filter out the specified props. The second generic represents the keys of the props that we want to keep.

After this, I simply iterate over the expected keys we want to keep, and for each key, I include it in a new object.

Working as the original pick utility:

Image description

I hope that this it will very helpful for you.

Follow me for more contents about TS stack.

Top comments (0)