0
0
Typescriptprogramming~5 mins

Extending interfaces in Typescript

Choose your learning style9 modes available
Introduction

Extending interfaces lets you build new interfaces from existing ones. This helps you reuse code and keep things organized.

You want to add more properties to an existing interface without changing it.
You have common properties shared by many interfaces and want to avoid repeating them.
You want to create a more specific version of a general interface.
You want to combine multiple interfaces into one.
You want to keep your code easy to read and maintain by breaking big interfaces into smaller parts.
Syntax
Typescript
interface BaseInterface {
  property1: any;
}

interface ExtendedInterface extends BaseInterface {
  property2: any;
}

The extends keyword is used to inherit properties from another interface.

The new interface gets all properties from the base interface plus any new ones you add.

Examples
Here, Employee has all properties of Person plus employeeId.
Typescript
interface Person {
  name: string;
  age: number;
}

interface Employee extends Person {
  employeeId: number;
}
Car extends Vehicle by adding the doors property.
Typescript
interface Vehicle {
  make: string;
  model: string;
}

interface Car extends Vehicle {
  doors: number;
}
C extends both A and B, combining their properties.
Typescript
interface A {
  a: string;
}
interface B {
  b: string;
}
interface C extends A, B {
  c: string;
}
Sample Program

This program shows how Dog extends Animal. The object myDog has all properties from both interfaces.

Typescript
interface Animal {
  name: string;
  age: number;
}

interface Dog extends Animal {
  breed: string;
}

const myDog: Dog = {
  name: "Buddy",
  age: 5,
  breed: "Golden Retriever"
};

console.log(`My dog's name is ${myDog.name}, age is ${myDog.age}, and breed is ${myDog.breed}.`);
OutputSuccess
Important Notes

You can extend multiple interfaces by separating them with commas.

If two interfaces have properties with the same name, they must have compatible types.

Extending interfaces helps keep your code DRY (Don't Repeat Yourself).

Summary

Extending interfaces lets you build new interfaces from existing ones.

Use extends keyword to inherit properties.

This makes your code cleaner and easier to maintain.