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.