Typescript Foundations / Working with Modules

Declaration Merging

Declaration Merging is a unique TypeScript feature where the compiler merges multiple declarations with the same name into a single definition.

🧠 It only applies to certain kinds of declarations like interfaces, namespaces, functions, classes, and enums.


✅ Interface Merging

When two interfaces with the same name are declared, TypeScript merges their properties.

interface User {
  name: string;
}

interface User {
  age: number;
}

const person: User = {
  name: "Tisha",
  age: 22
};

🔹 The resulting User interface is:

interface User {
  name: string;
  age: number;
}

🛑 But if the merged properties conflict, you’ll get a type error.


✅ Namespace Merging

You can extend a function, class, or enum by declaring a namespace with the same name.

function greet() {
  console.log("Hello!");
}

namespace greet {
  export const language = "English";
}

greet();                        // Hello!
console.log(greet.language);    // English

📌 This is useful for attaching metadata to functions or classes.


✅ Enum Merging

enum Direction {
  Up = 1,
}

enum Direction {
  Down,
  Left,
  Right,
}

console.log(Direction.Right); // 3

🔁 The enum members are merged and counted sequentially if not assigned.


✅ Class & Namespace Merging

You can use a namespace to augment a class with static properties or helper types.

class Animal {
  constructor(public name: string) {}
}

namespace Animal {
  export const species = "Mammal";
}

console.log(Animal.species); // Mammal

⚠️ Rules & Limitations

Type

Can be Merged?

Notes

Interface

✅ Yes

Merges properties

Namespace

✅ Yes

Merge namespaces or with classes/functions

Enum

✅ Yes

Members must not conflict

Function

✅ Yes (with namespace)

Metadata style use

Type Alias

❌ No

Type aliases cannot be merged


🚫 Type Alias – Not Mergeable

type A = { a: string };
// ❌ Cannot declare `type A` again

🧠 Use Cases

  • Adding methods or metadata to existing types

  • Extending 3rd-party types (e.g., augmenting Window or Jest)

  • Grouping related logic using namespaces