0
0
Typescriptprogramming~5 mins

Multiple interface extension in Typescript

Choose your learning style9 modes available
Introduction
Sometimes you want to create a new interface that combines properties from several other interfaces. This helps keep your code organized and reusable.
When you want to create a new type that has all properties from two or more interfaces.
When you want to build complex objects by combining simple interfaces.
When you want to avoid repeating properties in multiple interfaces.
When you want to clearly show that an object follows multiple contracts or shapes.
Syntax
Typescript
interface NewInterface extends Interface1, Interface2, Interface3 {
  // additional properties if needed
}
You list all interfaces to extend separated by commas.
The new interface will have all properties from the extended interfaces.
Examples
Dog interface combines Animal and CanRun properties, plus its own breed.
Typescript
interface Animal {
  name: string;
}

interface CanRun {
  speed: number;
}

interface Dog extends Animal, CanRun {
  breed: string;
}
Interface C has both a and b properties from A and B.
Typescript
interface A {
  a: number;
}

interface B {
  b: string;
}

interface C extends A, B {}
Sample Program
This program creates an Employee interface that combines Person and Worker. Then it creates an object emp with all properties and prints them.
Typescript
interface Person {
  name: string;
}

interface Worker {
  job: string;
}

interface Employee extends Person, Worker {
  salary: number;
}

const emp: Employee = {
  name: "Alice",
  job: "Developer",
  salary: 50000
};

console.log(`Name: ${emp.name}`);
console.log(`Job: ${emp.job}`);
console.log(`Salary: $${emp.salary}`);
OutputSuccess
Important Notes
If two extended interfaces have properties with the same name but different types, TypeScript will show an error.
You can add new properties in the extending interface besides the ones inherited.
Multiple interface extension helps keep your code clean and easy to understand.
Summary
Multiple interface extension lets you combine several interfaces into one.
The new interface has all properties from the extended interfaces.
It helps create complex types without repeating code.