Hello everyone!
Today I'll tell about a cool feature of TypeScript, which is the Partial utility type.
This utility type works on types (per definition, and as such won't work with interfaces, a mistake I personally made), and makes all of its properties optional.
Lets take this code for example:
Here, we have a Person
type, with some predefined properties with different types.
Now we want to create a new type with the same properties and their types, but they should all be optional.
We could insert the interrogation mark followed by a colon ?:
at each property, and indeed, that'll do the job, but as obvious, it is not the most efficient solution, not to mention that if we have an huge type, it can take some much valuable time that is better spent doing more productive tasks.
So what is the solution? The Partial
utility type.
This is how its done using the aforementioned utility type.
As you can see, its usage is really simple and straightforward. It accept a single generic (think of it as a TypeScript's parameter, but for types, instead for functions), which is the Type we want its properties to become optional.
Now, we hover over the new PartialPerson
type, we can see that all of the properties are now optional, and we didn't even have to know all of them beforehand.
Its definition per TypeScript is as follows:
They basically looped through all of the properties passed through the generic, and making each property optional with its type definition.
The main usage of it is the updating/editing tasks, when you want to edit an object through a function, but you only want to pass the object properties you intend to edit, and not all of them.
This feature is available in TypeScript since version 2.1
Bonus: You can use the Required
utility type to make all properties of a type required, and if some or all of its properties are optional, they become required. This is the opposite of Partial
, where all properties become optional.
Thank you for reading, and I hope that was beneficial to you!
Connect with me on:
Top comments (2)
I did not know this! Very cool, thank you for sharing!
Glad to hear that! You're most welcome!