0
0
Typescriptprogramming~5 mins

Declaration merging for interfaces in Typescript

Choose your learning style9 modes available
Introduction

Declaration merging lets you combine multiple interface definitions with the same name into one. This helps organize and extend code easily.

When you want to add new properties to an existing interface without changing the original code.
When different parts of your program define parts of the same interface separately.
When working with third-party libraries and you want to add extra properties to their interfaces.
When splitting interface definitions across multiple files for better code organization.
Syntax
Typescript
interface InterfaceName {
  property1: Type1;
}

interface InterfaceName {
  property2: Type2;
}

All interface declarations with the same name merge into one combined interface.

If properties have the same name, their types must be compatible or an error occurs.

Examples
Both interfaces merge into one with name and age properties.
Typescript
interface User {
  name: string;
}

interface User {
  age: number;
}
This creates a Config interface with debug and version.
Typescript
interface Config {
  debug: boolean;
}

interface Config {
  version: string;
}
Sample Program

This program shows how two interface declarations with the same name merge. The Person interface has both firstName and lastName. The object user uses both properties.

Typescript
interface Person {
  firstName: string;
}

interface Person {
  lastName: string;
}

const user: Person = {
  firstName: "Alice",
  lastName: "Smith"
};

console.log(`Full name: ${user.firstName} ${user.lastName}`);
OutputSuccess
Important Notes

Declaration merging only works with interfaces, not with types or classes.

Be careful to avoid property name conflicts with incompatible types.

Summary

Interfaces with the same name merge their properties into one.

This helps extend or organize interfaces across code.

Use declaration merging to add properties without changing original interface code.