To easily make a new type by taking or picking certain properties from another type in TypeScript, you can use the Pick
utility type and pass the name of the type you want to take the properties from as its first type argument, and the properties you need to pick as a string literal union type as its second type argument.
TL;DR
// a simple interface
interface Person {
name: string;
age: number;
salary: number;
}
// make new type by picking the `name`
// and `age` properties from the `Person` interface
// using the `Pick` utility type
type NecessaryDetails = Pick<Person, "name" | "age">;
/*
Content of `NecessaryDetails` type
{
name: string;
age: number;
}
*/
For example, let's say we have an interface called Person
with some properties called name
having the type of string, age
having the type of number
, and salary
having the type of number
like this,
// a simple interface
interface Person {
name: string;
age: number;
salary: number;
}
Now let's say we need to make a new type where we need only the name
and age
properties from the Person
interface, to do that we can use the Pick
utility type and pass the Person
type as its first type argument and a string literal union type composed of name
and age
as its second type argument like this,
// a simple interface
interface Person {
name: string;
age: number;
salary: number;
}
// make new type by picking the `name`
// and `age` properties from the `Person` interface
// using the `Pick` utility type
type NecessaryDetails = Pick<Person, "name" | "age">;
/*
Content of `NecessaryDetails` type
{
name: string;
age: number;
}
*/
Now if you hover over the NecessaryDetails
type, you can see that the name
and age
properties are picked from the Person
interface and is now available in the NecessaryDetails
type.
We have successfully made a new type by taking or picking certain properties from another type in TypeScript. Yay 🥳!
See the above code live in codesandbox.
That's all 😃!