π When one interface inherits properties from another, it's called extension.
π Use the extends keyword to create a new interface based on an existing one.
β Basic Syntax
interface Base {
id: number;
}
interface User extends Base {
name: string;
email: string;
}Now User has all properties from both Base and itself:
const u1: User = {
id: 1,
name: "Tisha",
email: "tisha@example.com"
};β¨ Why Use Extension?
β DRY (Don't Repeat Yourself)
β Promotes reusability
β Helps with large-scale applications
β Useful for OOP-style modeling (like base classes)
π Extending Multiple Interfaces
You can extend more than one interface by comma-separating them:
interface Timestamped {
createdAt: Date;
updatedAt: Date;
}
interface Identified {
id: string;
}
interface Post extends Timestamped, Identified {
title: string;
content: string;
}const blogPost: Post = {
id: "p1",
title: "Intro to TypeScript",
content: "Great for large JS apps",
createdAt: new Date(),
updatedAt: new Date()
};π§ Optional and Readonly Properties Work Too
interface Person {
readonly id: number;
name: string;
age?: number;
}
interface Employee extends Person {
department: string;
}β Interface Extension with Methods
interface Animal {
name: string;
speak(): void;
}
interface Dog extends Animal {
breed: string;
}
const pet: Dog = {
name: "Tommy",
breed: "Beagle",
speak() {
console.log("Woof!");
}
};π Interface vs Type with &
You can achieve similar behavior with type using intersection:
type A = { id: number };
type B = { name: string };
type C = A & B;
const obj: C = { id: 1, name: "Tisha" };Feature |
|
|
|---|---|---|
Object extension | β
| β
|
Declaration merging | β | β |
Non-object types | β | β |
β Summary
Concept | Syntax |
|---|---|
Extend one interface |
|
Extend multiple |
|
Combine methods, optional & readonly | β Supported |
Reusable for large apps | β Best practice |