TypeScript
/Intermediate
Pick<T, Keys>
Definition
A utility type that constructs a new type by selecting a specific set of properties (`Keys`) from an existing type (`T`).
Explain Like I'm New
Imagine a massive buffet table with 50 dishes (Type T). `Pick` is your plate. You specifically name the 3 dishes you want (`Keys`), and TS creates a customized plate with ONLY those 3 dishes.
Real World Example
You have a massive `User` interface with 30 fields (passwords, timestamps, role). You are building a 'UserPreview' UI component that only needs the `name` and `avatar`. `type UserPreview = Pick<User, 'name' | 'avatar'>`.
Common Use Cases
- •Extracting UI component props from massive API interfaces
- •Keeping types DRY
Interactive Example
interface FullArticle { id: number; title: string; body: string; authorId: number; publishedAt: Date; isDraft: boolean; } // We only want the title and body for the preview card type ArticlePreview = Pick<FullArticle, "title" | "body">; const preview: ArticlePreview = { title: "TypeScript is Awesome", body: "Here is why..." // TS will error if we try to add 'id' or 'authorId' here! };
Interview Questions
basic
- How do you pick multiple keys at once?
intermediate
- What happens if you try to `Pick` a key that doesn't exist in the original type?