TypeScript’s Pick
and Omit
are two utility types that allow you to create new types based on existing types. These types can be very useful in creating new types that are more specialized for a specific use case.
Pick
The Pick type allows you to create a new type by selecting only the specified properties from an existing type. Here’s an example:
|
|
In this example, PersonNameAndAge
is a new type that only includes the name
and age
properties from the Person
type. The syntax for using Pick
is as follows:
|
|
Here, Type
is the type you want to pick properties from, and Keys
is a union of the keys you want to include in the new type.
Omit
The Omit
type allows you to create a new type by excluding the specified properties from an existing type. Here’s an example:
|
|
In this example, PersonWithoutEmail
is a new type that includes all the properties from the Person
type except for the email
property. The syntax for using Omit
is as follows:
|
|
Here, Type
is the type you want to exclude properties from, and Keys
is a union of the keys you want to exclude from the new type.
Cheer! 🍺