Objects 16 exercises
solution

Extending Interfaces to Create Hierarchies in TypeScript

Interfaces in TypeScript are great for creating hierarchies between types.

Instead of using the type keyword, the BaseEntity, User, and Product, can be declared as interfaces. Note that interfaces do not use an equals sign like type does:


interface BaseEntity {
id: string;

Loading solution

Transcript

00:00 Okie dokie. Interfaces can be used to create hierarchies between types, and they're pretty nice. What we can do is instead of using type here, we can declare these as interfaces. Now interfaces, what you'll see is first of all, you get red lines everywhere. That's because interfaces don't use this little equals sign here.

00:19 So we can remove all of those. And they also can't be added to with an and here. So interfaces can only represent a certain number of things here. And really what they're most used for is representing object types. So now we've got our interface of user and interface of product. Interface user represents an object with a name and email.

00:39 And product represents an object with a name and price. So what we want to do is we want to say you need to inherit from base entity. And for that, we can use the extends keyword. We can say extends base entity. And now interface user extends base entity.

00:58 This means it inherits all the properties from base entity and it adds it to it. So now user is this type here. It's ID string, created at date, name string, email string. Beautiful. We can go further if we want to. We can say instead of base entity, we can actually say with ID and with created at.

01:17 So we could actually go all the way down to this, have an interface of with ID, have an interface of with created at. And then use a comma to separate them and say extends with ID with created at. So you can see you can get kind of wild here. And interfaces let you behave in TypeScript as if you're in like an object oriented environment.

01:37 They give you a first class primitive for doing this kind of inheritance between types. And it's really, really smart stuff. And in the next exercise, we'll compare between types and interfaces and sort of see which one you should probably be using.