What does Pick<T, K> do?
1. What Pick<T, K> does
Pick<T, K>creates a new type that contains only the specified fieldsKfrom the source typeT.
Syntax
Pick<SourceType, 'key1' | 'key2' | ...>Example
interface User {
id: number;
name: string;
email: string;
age: number;
}
// create a type with only id and name
type UserPreview = Pick<User, 'id' | 'name'>;Now UserPreview is equivalent to:
{
id: number;
name: string;
}The other fields (
age) are excluded.
2. How to select only the needed fields from an interface
Just pass the names of the needed properties as the second argument (K):
type UserShort = Pick<User, 'name' | 'email'>;
const u: UserShort = {
name: "Tim",
email: "tim@example.com",
};You can select one or several properties, combining them with
|.
3. How Pick works internally
The built-in implementation looks like this:
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};Breakdown:
K extends keyof Trestricts the list of keys to only those present inT;[P in K]creates a new object made up of the selected keys;T[P]preserves the original property types.
4. What happens if you specify a field that doesn't exist
TypeScript immediately produces a compile-time error,
because K must be a subset of the keys of T.
An error example
type Wrong = Pick<User, 'id' | 'nickname'>;
// Error: Type '"nickname"' is not assignable to keyof 'User'TypeScript strictly checks that
'nickname'is not inUser.
5. Usage in real projects
Example 1. A DTO or API response
interface User {
id: number;
name: string;
email: string;
password: string;
}
// a safe type without the password
type PublicUser = Pick<User, 'id' | 'name' | 'email'>;Used to restrict the set of properties before returning data.
Example 2. Preview objects
interface Product {
id: number;
title: string;
description: string;
price: number;
}
type ProductCard = Pick<Product, 'id' | 'title' | 'price'>;A product card does not need all the fields, just the basic information.
Example 3. Combining with other Utility Types
type OptionalName = Partial<Pick<User, 'name'>>;First select the needed field (
Pick), then make it optional (Partial).
6. The key difference from Omit<T, K>
| Utility | What it does | Example |
|---|---|---|
Pick<T, K> | Keeps the specified fields | `Pick<User, 'id' |
Omit<T, K> | Excludes the specified fields | Omit<User, 'password'> |
Summary
| Question | Answer |
|---|---|
What does Pick<T, K> do | Creates a new type that includes only the selected properties from T |
| How to select the needed fields | Specify them as the second parameter (`'field1' |
| What happens with a non-existent field | TypeScript produces a compile-time error ("X" is not assignable to keyof T) |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.