Beginner's TypeScript Tutorial (18 exercises)
solution

Extend Interfaces From Other Interfaces

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

interface Base {
  id: string;
}

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

interface User extends Base {
  firstName: string;
  lastName: string;
}

interface Post extends Base {
  title: string;
  body: string;
}

interface Comment extends Base {
  comment: string;
}

Adding extends Base makes it so the types inherit the properties of the Base interface.

Note that if the User, Post, and Comment were defined using the type keyword, we would not be able to use extends:

// This won't work!
type Base {
  id: string;
}

// Syntax errors
type Comment extends Base {
  comment: string;
}

This is because extends is a property of interface that type doesn't have.

Interfaces can extend from other interfaces. This allows us to change things in just one place, which is really useful.

It's even possible to extend multiple interfaces.

For example, we can have Post extend from Base and User:

interface Post extends Base, User {
  title: string;
  body: string;
}

Then when creating a new post variable, we would have autocomplete on all of the properties required.

Interfaces can be composed together in a neater way than if we were just using types alone. This is particularly useful for situations where we have a complex data model that you want to express in TypeScript.

Transcript

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.

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.

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.

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.

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.