Objects 16 exercises
solution

Use the Intersection Operator to Extend an Object Type in TypeScript

To solve this challenge, we'll create a new BaseEntity type with the common properties:


type BaseEntity = {
id: string;
createdAt: Date;
};

Once the BaseEntity type is created, we can use it to create the User and Product types that intersect it:


type

Loading solution

Transcript

00:00 Okay, let's take the properties that we have in common between user product and create a new type from them type base entity is now ID and created at we now have an error down the bottom, of course, because user no longer corresponds to the contract that we want it to, but if we give it an intersection and we say and base entity, then it starts working.

00:22 And now we can do the same with product here and we can have and base entity attached to product to lovely. So now user and product are both types that are mashed together out of these two pieces. Nice. And now they have exactly the same behavior as they had before. They've just got a little bit of less duplication. We've reduced like one line of code here and we've got a pattern that we can reuse no matter how many of these entities we can create.