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>
Type
is the original type you are modifying.Keys
is 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
Person
and you want to create a new type that includes only thename
property:Terminaltype Person = {name: stringage: numberemail: string}type JustName = Pick<Person, 'name'>JustName
will have only thename
property.
Picking multiple properties:
To pick more than one property, you can list them in the
Pick
utility separated by pipes (|
):Terminaltype NameAndEmail = Pick<Person, 'name' | 'email'>This will create a type that includes both the
name
andemail
properties.
Using
Pick
in functions:Pick
is 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
email
property.
Omit
vs Pick
in TypeScript
Usage:
Pick
andOmit
are complementary utilities in TypeScript.Pick
is used when you know which properties you want to include, whileOmit
is 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
PickedPerson
andOmittedPerson
will result in an object type that includes thename
andemail
properties, 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.