Beginner's TypeScript #14
Nhan Nguyen
Posted on January 2, 2024
⭐ 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;
}
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;
}
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 will not work!
type Base {
id: string;
}
// Syntax errors
type Comment extends Base {
comment: string;
}
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;
}
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Posted on January 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.