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.
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
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!