Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use Partial to Create Partially Fillable Types in TypeScript

    Kamran AhmedKamran Ahmed

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Kamram Ahmed: 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.

    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.

    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.

    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.

    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.