Two Useful Utility Types in Typescript: “Partial” and “Pick”
The Typescript documenation sets out a dozen of utility types. After using some of them, I was fasinated. They made my code much neater. I did not know even they are existing before.
In case you are missing them like me 2 days ago, I will breifly introduce the concept of utility types and two of them I frequently use.
What are “utility types” in Typescript ?
When you work on Typescript projects, you may encouter a situation where you are tempted to construct a new type that is just “slightly” different from an existing one.
As a developler who takes the DRY(“Don’t Repeat Yourself”) principle very seriously, you also know that repeating the existing type is not a good practice.
That is when to use utility types. It gives you a way to create a new type on top of the existing one without repeating or changing the existing one.
Let me give you a few examples to explain better.
A Existing Type: Organization
Suppose you already have a type, “Organization”. It looks like as follows.
Most of the time, you just need to use the type, Organization. When you read or create an Organization-typed object, there is no problem.
However, what if you should send a http request updating the address property of the object? Will you create a new type like the one below?
What if you need to update another property, name? Will you make another one? or What if you need to update two properties like “name” and “nationality” at once. Will you make another one?
No. You should not do that~ We have “Partial” and “Pick” in Typescript.
“Partial” sets all properties of Type optional. Say you have an organization-typed object, “Apple”.
Partial<Organization> sets all the 5 keys optional. It is useful when you send request for updating a part of the Type’s property.
The following code sends a post request to update Apple’s address by using Axios.
It is neat.
2. Pick<Type, Keys>
You may not like “Partial” because it does not specify which property or properties of Apple will be updated. “Pick” solves the problem. As its name implies, “Pick” lets you pick specific Keys in the Type, “Organization”
“Pick” provides more Typescript-like way of constructing a partial type.
There are more nice and useful utility types in Typescript. I am trying to be familiar with all of them. Before that, I wanted to share ones that I am using most frequently. I hope you enjoyed my post.
Thanks for reading.