In the previous article, Utility types in Typescript - Part 1, we looked at three of the commonly used utility types in Typescript.
In this article, we will consider some more examples of built-in utility types provided by Typescript and how we can use them in code.
The utility type Pick
creates a new type with only the specified Keys
of the input type T
.
interface Point {
x: number;
y: number;
z: number;
}
type PointXY = Pick<Point, "x" | "y">;
// {
// x: number;
// y: number;
// }
In the code above, we have an interface Point
which has 'x' | 'y' | 'z'
as keys. Using the Pick
utility type we can create a type PointXY
by only picking the keys 'x' | 'y'
from the interface.
The Pick
utility type is useful if we need to get a subset of properties from an object as seen in the example below.
interface User {
name: string;
age: number;
email: string;
password: string;
address: string;
city: string;
}
type UserAddress = Pick<User, "address" | "city">;
const address: UserAddress = {
address: "No 1 ABC Street",
city: "Port Harcourt",
};
The utility type Omit
creates a new type by picking all properties from the input type T
and then removing the specified Keys
. It does the opposite of Pick
.
interface Point {
x: number;
y: number;
z: number;
}
type PointXY = Omit<Point, "z">;
// {
// x: number;
// y: number;
// }
The Omit
utility type is useful if we need to get rid of certain properties from an object (perhaps sensitive information) as seen with the example below.
interface User {
name: string;
age: number;
email: string;
password: string;
address: string;
city: string;
}
type UserProfile = Omit<User, "address" | "city" | "password">;
const profile: UserProfile = {
name: "Anderson",
age: 27,
email: "[email protected]",
};
The utility type Record
creates a new object type. The keys in this new object type are the values passed as K
while the values are what is passed in as T
.
type Axes = "x" | "y" | "z";
type Point = Record<Axes, number>;
// {
// x: number;
// y: number;
// z: number;
// }
The Record utility type is useful when we want to type an object whose keys have a similar type of value. A common example is while normalizing complex data.
interface UserInfo {
id: number;
name: string;
age: number;
}
const data: UserInfo[] = [
{
id: 1,
name: "Ande",
age: 28,
},
{
id: 2,
name: "Mosa",
age: 25,
},
];
const userList: Record<string, UserInfo> = {
"1": {
id: 1,
name: "Ande",
age: 28,
},
"2": {
id: 2,
name: "Mosa",
age: 25,
},
};
In this article and the previous one, we have looked at some commonly used utility types provided by Typescript and how we can use them in code. These utility types help developers to avoid hard-coding types.
There are a lot more utility types apart from those mentioned in these articles. The Typescript documentation contains a list of all the available utility types.