Article summary
I’ve been primarily coding in TypeScript for over two years and am comfortable with its syntax and conventions, but still enjoy learning new tricks to improve my expertise. Here are some utility types I discovered recently that may help you improve code readability and quality.
Pick and Omit
Let’s say you created a type called User
.
type User = {
id: string;
name: string;
age: number;
email: string;
phone: string;
createdAt: Date;
};
If you want to create a related type that has only a few of the properties from User
, you can use the Pick utility.
type ContactInfo = Pick<User, "email" | "phone">;
const contactSources: ContactInfo = {
email: "[email protected]",
phone: "4445556666"
};
This is useful for showing how different objects are related to each other. You can create a new type with the properties email
and phone
without using Pick, but it may be less clear that this object is related to User.
Omit is the reverse of Pick, allowing you to grab all of a type’s properties and then remove specific keys.
type ProfileData =
Omit<User, "id" | "createdAt">;
const userProfile: ProfileData = {
name: "Link"
age: 50;
email: "[email protected]";
phone: "1234567890";
}
Both Pick and Omit allow you to create a new type that transforms the original. This makes them easier to debug if the type you are transforming is later modified. For example, if the property age
is removed from User, you will see an error in userProfile
.
Prettify
Prettify isn’t a globally available TypeScript helper but a self-implemented type that makes hover overlay easier to read.
Simply define the following type in your code:
type Prettify = {
[K in keyof T]: T[K];
} & {};
The following type with multiple object intersections may look messy initially:
type ItemInfoCombined =
{ productName: string;
id: string;
} & { category: string; } & {
isAvailable: boolean;
}
If you wrap it in Prettify and hover over the type, all intersected objects are flattened into one:
type ItemInfoCombined = Prettify<
{ productName: string; id: string }
& { category: string }
& { isAvailable: boolean; } >;
Since Prettify is undocumented, it’s not entirely clear why intersecting with an empty object works, but it’s some result of TypeScript’s compiler logic. Interestingly, intersecting this type with unknown
in place of {}
has the same effect on the formatting.
These are only a few of the many utilities available in TypeScript. Try them out and see if they help you improve the quality of your code.