Objects 16 exercises
Problem

Extending Objects in TypeScript

In TypeScript, the intersection character (&) serves to combine or intersect multiple types, similar to the functionality of the union character (|).

However, while the union character could be thought of as representing 'or' between different types, the intersection character represents 'and'

Loading exercise

Transcript

00:00 In this exercise, we're going to introduce the intersection character. We've seen the union sort of vertical bar thing. Well, you can use the ampersand in TypeScript just here to basically do combinations of objects. So, for instance, if I had a type A and let's say it's got a string inside it,

00:18 then I can say type B equals B string. Then to create C or let's say A and B, I can say A and B like this. If I were to create a union of this, then I would say A or B. But this in TypeScript is the other equivalent. So this is the and.

00:38 And we can see here that if I say const example is A and B, then I have to provide A and B in order to satisfy that contract. So now knowing that, now knowing that we've got this sort of ampersand thing at our disposal that we can use to make kind of reusable types here,

00:57 we're going to look at some types that we're going to refactor. So we have a user type here and we have a product type. We have some a little bit of duplication between them where we have an ID and a created at type or properties on this type that is duplicated between both of these. And you can imagine if we had 20 of these,

01:17 we might want to extend this into a reusable type that we could intersect with both of these types to kind of get it working. We have some tests here that are testing to make sure that user and product stay in the correct shape here. But what I'd like you to do is change the definition for user and product so that

01:35 they rely on the same like sort of base entity that has ID and created at on it. This means that later down the line, we can kind of sort of create a bunch of these and create a reusable pattern where we don't have to duplicate things. And if, for instance, we want to add updated at in the future, then we can. So that's your job. Using this little intersection thing,

01:56 try to find a way to keep the code working, but also create a sort of little dry piece of user and product that we can then use later to create other entities out of. Good luck.