Extending Interfaces
In this page:
Basic Interface Extension
The extends keyword lets one interface build on another, inheriting all of the base interface's properties automatically. This avoids repeating shared fields across multiple related interfaces and keeps the relationship between them explicit in the code.
Example: Basic Interface Extension
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const dog: Dog = { name: "Rex", breed: "Labrador" };
console.log(dog);
Adding More Properties
An interface that extends another can add any number of new properties on top of everything it inherits. Objects satisfying the extended interface must include both the inherited properties and every newly added one.
Example: Adding More Properties
interface Person {
name: string;
}
interface Employee extends Person {
employeeId: number;
department: string;
}
const emp: Employee = { name: "Lena", employeeId: 7, department: "IT" };
console.log(emp);
Extending Multiple Interfaces
A single interface can extend more than one other interface at once, combining all of their members into one required shape. This is a common way to compose several smaller, focused interfaces into one larger contract.
Example: Extending Multiple Interfaces
interface Named {
name: string;
}
interface Aged {
age: number;
}
interface Person extends Named, Aged {}
const person: Person = { name: "Omar", age: 40 };
console.log(person);
Extending Interfaces with Methods
Child interfaces inherit any method signatures declared on their parent interfaces and can add entirely new methods of their own on top. This lets a hierarchy of interfaces build up an increasingly specific and complete contract as it extends downward.
Example: Extending Interfaces with Methods
interface Shape {
area(): number;
}
interface ColoredShape extends Shape {
color: string;
}
const square: ColoredShape = { color: "red", area: () => 16 };
console.log(square.color, square.area());
Building Interface Hierarchies
Interfaces can be extended through several levels to build reusable hierarchies, where a base interface captures the most general shape and each level down adds more specific requirements. This mirrors class inheritance but purely at the level of type shapes.
Example: Building Interface Hierarchies
interface Base {
id: number;
}
interface WithName extends Base {
name: string;
}
interface WithEmail extends WithName {
email: string;
}
const user: WithEmail = { id: 1, name: "Priya", email: "[email protected]" };
console.log(user);
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: