Beginner's TypeScript #14

nhannguyendevjs

Nhan Nguyen

Posted on January 2, 2024

Beginner's TypeScript #14

Image description

Inheriting Interface Properties

We have a User, Post, and Comment that all share an id property:

interface User {
  id: string;
  firstName: string;
  lastName: string;
}

interface Post {
  id: string;
  title: string;
  body: string;
}

interface Comment {
  id: string;
  comment: string;
}
Enter fullscreen mode Exit fullscreen mode

We will figure out how to share the id property without writing the same line of code repeatedly.

🌟 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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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 will not work!
type Base {
  id: string;
}

// Syntax errors
type Comment extends Base {
  comment: string;
}
Enter fullscreen mode Exit fullscreen mode

This is because extends is a property of interface that type does not have.

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

It is 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;
}
Enter fullscreen mode Exit fullscreen mode

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 we want to express in TypeScript.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

💖 💪 🙅 🚩
nhannguyendevjs
Nhan Nguyen

Posted on January 2, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Beginner's TypeScript #tips
programming Beginner's TypeScript #tips

January 24, 2024

Beginner's TypeScript #27
programming Beginner's TypeScript #27

January 19, 2024

Beginner's TypeScript #26
programming Beginner's TypeScript #26

January 18, 2024

Beginner's TypeScript #25
programming Beginner's TypeScript #25

January 17, 2024