Use Partial to Create Partially Fillable Types in TypeScript

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson, we learn how to use TypeScript's Partial types to make the required properties of your types optional; allowing you to reuse the same types for the cases where you may not have all the data.

Kamram Ahmed: [00:00] Here we have a type called user, with two required properties, name and age. Then, we are creating a new user object of this type and then just printing the values here.

[00:08] Let's say that we have a case where we have this data partially, or we don't have this data at all. This will not work, because both of the fields are required in our type. To fix this, we can create a new type called PartialUser, where we have both of these fields as optional. Then, we use this type for our object. Now it will work with empty object. Also, it will work with the partial data.

[00:30] We have a problem here, that whenever we add some new field to our type user, let's say we add gender, we will still not be able to use it in our object, because it is not a part of our PartialUser type. We'll have to copy it from here and paste it here as optional. We'll be maintaining our user type in two places.

[00:52] To fix this, TypeScript has a better way to do this. We can type the same thing as type PartialUser is partial of type user.

[01:02] We're just telling type from that this PartialUser type can have partially filled user object. If we remove one of these fields, or if we make this object empty, it will still work in both the cases.

egghead
egghead
~ 8 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today