DEV Community

Marouane Souda
Marouane Souda

Posted on

The Partial utility type in TypeScript

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:

Image description

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.

Image description

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.

Image description

Its definition per TypeScript is as follows:

Image description

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)

Collapse
 
andrews1022 profile image
andrew shearer

I did not know this! Very cool, thank you for sharing!

Collapse
 
marsou001 profile image
Marouane Souda

Glad to hear that! You're most welcome!