Utility Type Pick in TypeScript
Pick is a utility type in TypeScript that allows "picking" specific properties from an existing type or interface. It creates a new type including only those fields you explicitly specified.
Syntax
Pick<T, K>
T- original type or interface from which to pick properties.K— union of keys you want to keep in resulting type.
Pick takes only listed properties K from T, and ignores all others.
When to use Pick?
- If you need to create new object type with limited number of properties.
- For API requests when not all data needs to be sent.
- In React props when component needs only specific data set.
Pick Usage Example
Suppose we have a User interface with several fields:
interface User {
id: number;
name: string;
age: number;
isAdmin: boolean;
}
If we need a type where we want to store only id and name, we can use Pick:
type BasicUserInfo = Pick<User, "id" | "name">;
const userInfo: BasicUserInfo = {
id: 1,
name: "Alice",
};
userInfo.age = 25;
// Error: property 'age' is missing in type 'Pick<User, "id" | "name">'
BasicUserInfocontains only fieldsidandname.- Attempting to access
ageorisAdminwill lead to compilation error as they're not in resulting type.
API Example
When getting user data from API sometimes you want to return outward only minimal set of fields without revealing entire internal object structure. For example:
interface User {
id: number;
name: string;
email: string;
passwordHash: string;
isAdmin: boolean;
}
// Create public profile (only safe data part)
type PublicUserProfile = Pick<User, "id" | "name">;
function getPublicProfile(user: User): PublicUserProfile {
return {
id: user.id,
name: user.name,
};
}
Thus, getPublicProfile function returns only those fields id and name that we explicitly specified in PublicUserProfile.
Why Pick?
- Type reduction: If you work with large interface and in specific context need only few properties,
Pickallows avoiding code duplication when defining types, reusing existing structures. - Flexibility: Allows dynamically reusing common data structures (e.g., when working with API), selecting only needed fields for specific operation.
- Control: Avoid accidentally passing extra data or unwanted properties.
Comparison with Omit
| Utility | Description |
|---|---|
Pick<T, K> | Leaves only specified properties K from T |
Omit<T, K> | Excludes specified properties K from T, leaving rest |