TypeScript's Pick utility allows you to create new types by picking a set of properties from an existing type. This is useful when you need to create a simplified version of a type with only a few properties from a larger type. This guide will explore how to use the Pick utility effectively, compare it with Omit, and apply it to various scenarios, including creating a date picker in TypeScript.
What is TypeScript's Pick utility?
The Pick type is a utility in TypeScript that constructs a new type by picking a set of properties from an existing type. The syntax for Pick is:
Pick<Type, Keys>
Typeis the original type you are modifying.Keysis the property or properties to pick from theType.
How to use Pick in TypeScript
Here’s a step-by-step process on how to use Pick:
Picking a single property:
Suppose you have a type
Personand you want to create a new type that includes only thenameproperty:Terminaltype Person = {name: stringage: numberemail: string}type JustName = Pick<Person, 'name'>JustNamewill have only thenameproperty.
Picking multiple properties:
To pick more than one property, you can list them in the
Pickutility separated by pipes (|):Terminaltype NameAndEmail = Pick<Person, 'name' | 'email'>This will create a type that includes both the
nameandemailproperties.
Using
Pickin functions:Pickis useful in functions where you want to ensure certain properties are passed:Terminalfunction sendEmail(person: Pick<Person, 'email'>) {// function body}This function will accept an object that must include the
emailproperty.
Omit vs Pick in TypeScript
Usage:
PickandOmitare complementary utilities in TypeScript.Pickis used when you know which properties you want to include, whileOmitis used when you know which properties you want to exclude.
Example:
Terminal// Using Picktype PickedPerson = Pick<Person, 'name' | 'email'>// Using Omittype OmittedPerson = Omit<Person, 'age'>Both
PickedPersonandOmittedPersonwill result in an object type that includes thenameandemailproperties, but the approach differs based on whether you are excluding or including properties explicitly.
Creating a date picker in TypeScript
If you are working on a project that requires a date picker, you can define its type using Pick to simplify the integration with other types. For instance:
interface DatePickerProps {value: DateonChange: (date: Date) => void}// Using Pick to create a simplified DatePicker typetype SimpleDatePicker = Pick<DatePickerProps, 'value' | 'onChange'>function DatePicker({ value, onChange }: SimpleDatePicker) {// DatePicker implementation}
This example picks only the essential properties from a more complex DatePickerProps type to create a simplified SimpleDatePicker type, which can be easier to handle in small components or utilities.
For further reading on the TypeScript Pick utility see the official documentation.