Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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.
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.
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">'
BasicUserInfo contains only fields id and name.age or isAdmin will lead to compilation error as they're not in resulting type.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.
Pick allows avoiding code duplication when defining types, reusing existing structures.| Utility | Description |
|---|---|
Pick<T, K> | Leaves only specified properties K from T |
Omit<T, K> | Excludes specified properties K from T, leaving rest |