Another utility type that TypeScript gives us is Pick
. Pick
allows us to choose what properties we want from an object to use with a new object, for example. Pick
’s structure is as follows: Pick<Type, Keys>
.
Example
Suppose we have the following object of type User
:
const employee: User = {
firstName: 'Tom',
lastName: 'Smith',
department: 'Engineering',
position: 'Technical Lead'
}
We want to create an object which only contains a first name and last name. We will implement this using Pick
in the following manner:
type FullName = Pick<User, "firstName" | "lastName">;
const userFullName: FullName = {
firstName: 'Peter',
lastName: 'Johnson'
};
console.log(userFullName) // {firstName: "Peter", lastName: "Johnson"}