Member-only story
Demystifying TypeScript’s Pick Utility Type
Pick
allows you to create a new type by selecting properties from an existing type. It's like handpicking only the properties you need from a larger object. Let's delve into how you to usePick
.
Understanding the Basics
Consider a scenario where you have an interface defining a user object:
interface User {
id: number;
name: string;
email: string;
age: number;
}
Now, imagine you want to create a new type that only includes id
and name
properties from this interface. This is where Pick
shines:
type UserPreview = Pick<User, 'id' | 'name'>;
Here, UserPreview
is a new type comprising only the id
and name
properties from the User
interface.
Syntax
The syntax for Pick
is
type NewType = Pick<ExistingType, Keys>;
NewType
: This represents the new type that will be created with the chosen properties.ExistingType
: This refers to…