Merge Types using Intersection Operator

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet

There might be times when you want to extend a type, i.e., to add new fields to it. Instead of copying the types and creating duplicates, the better way to do that is to use the intersection operator &. In this quick lesson, you will learn what it does and how you can use it to reduce duplicate types.

[00:00] Here we have a user type with name, age, and location, and we're using this type in this user object with some dummy data. Let's say that we need a new user DB type, but we need to add ID to the same user type. There are 2 ways to do this. The first one is that we copy this user type and we add a new user db type, and we add the id [00:20] to this type. But the issue with this approach is if we need to add more data to this user type, we'll have to modify this type as well. The better way to do this would be to use the same user type and somehow add more fields to that. Now if you see here, we're getting the error that ID is not a known field. To fix this, all we need to do is use the [00:40] intersection operator to merge the user type with ID colon string. You can add as many fields as you want, and what the intersection operator will do is it will take the types on both sides of the operator and merge them together into a new type. And now if you see here, our error is gone.