Beginner's TypeScript Section 18 exercises

Extend Interfaces From Other Interfaces

The first thing to do is create a new Base interface with the id property:

With that in place, we can use the extends keyword with each of the other interfaces and remove the id:

Loading solution


0:00 Now we have a base interface. This base interface, it contains our ID string, and now each of user, post, and comment will inherit from that base interface using extends.

0:13 This is a property of interface that type doesn't have. If these were types instead, we wouldn't be able to do this in the same way. In fact, we're now littered with syntax errors.

0:25 Interfaces can extend from other interfaces, which is really, really useful. What it means is that if I want to change number here, or change ID to number, then I only need to change it in one place, which is extremely useful.

0:40 If I just changed the tests to work, then that's going to do the same thing. This is really, really nice. We can even have it so that it extends a couple of different things if we want to. Post now extends base and user. If I want to add const post is a post here, then I need to add body, first name, title, or last name.

1:03 This means that you can compose interfaces together in a neater way than if you were just using types. This syntax is pretty useful for some situations, especially if you have this complex data model that you want to express in TypeScript.