Extending Interfaces with extends
What you'll learn: How to build interface hierarchies by extending one interface from another to share and reuse common properties.
Why Extend Interfaces?
Just like you might have a base "Vehicle" concept that cars and trucks build upon, TypeScript lets you create a base interface and extend it to create more specific versions. This avoids duplicating shared properties across multiple interfaces.
The extends Keyword
When you use extends, the new interface inherits all properties from the base interface and can add its own:
interface Animal {
name: string;
age: number;
}
interface Dog extends Animal {
breed: string;
bark(): void;
}
Now Dog has name, age, breed, and bark. You don't need to repeat the Animal properties.
Using Extended Interfaces
Objects must satisfy all properties from the entire hierarchy:
const myDog: Dog = {
name: "Buddy",
age: 3,
breed: "Golden Retriever",
bark() {
console.log("Woof!");
}
};
Extending Multiple Interfaces
You can extend more than one interface at once (comma-separated):
interface Swimmer {
swim(): void;
}
interface Flyer {
fly(): void;
}
interface Duck extends Animal, Swimmer, Flyer {
quack(): void;
}
Duck now has properties from Animal, Swimmer, Flyer, plus its own quack method.
Building Hierarchies
This approach creates clear type hierarchies and promotes reusability. Instead of copying properties, you build layers of specificity.
Key Takeaway: Use extends to inherit properties from one or more base interfaces, creating reusable type hierarchies without duplication.