0
0
Typescriptprogramming~3 mins

Why Pick type in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could grab just the pieces you need from a big type without rewriting everything?

The Scenario

Imagine you have a big object with many properties, but you only need a few specific ones for a task. Manually copying or extracting these properties one by one can be tedious and error-prone.

The Problem

Manually selecting properties means writing repetitive code, risking typos, and making your code harder to maintain. If the original object changes, you must update all manual selections everywhere.

The Solution

The Pick type lets you create a new type by selecting only the properties you want from an existing type. This keeps your code clean, safe, and easy to update.

Before vs After
Before
type User = { name: string; age: number; email: string; };
type UserNameAndEmail = { name: string; email: string; };
After
type User = { name: string; age: number; email: string; };
type UserNameAndEmail = Pick<User, 'name' | 'email'>;
What It Enables

It enables you to reuse and reshape types effortlessly, making your code more flexible and less error-prone.

Real Life Example

When building a user profile form, you might only need the user's name and email, not their age or other details. Pick type helps you define exactly that subset.

Key Takeaways

Pick type extracts specific properties from a larger type.

It reduces repetitive and error-prone manual type definitions.

It keeps your code clean, maintainable, and flexible.