0
0
Typescriptprogramming~5 mins

Declaration merging for namespaces in Typescript

Choose your learning style9 modes available
Introduction

Declaration merging lets you combine multiple pieces of code with the same name into one. For namespaces, this means you can add more things to a namespace in different places.

You want to organize related functions or variables under the same namespace but in different files.
You need to extend a namespace with new features without changing the original code.
You want to split a big namespace into smaller parts for easier maintenance.
You want to add helper functions to a namespace after it was first created.
Syntax
Typescript
namespace MyNamespace {
  // first part
}

namespace MyNamespace {
  // second part
}

Both namespace blocks must have the same name to merge.

All merged parts combine into one namespace when the program runs.

Examples
This example shows two parts of the same namespace Animals. Both functions become part of one namespace.
Typescript
namespace Animals {
  export function dog() {
    console.log('Woof!');
  }
}

namespace Animals {
  export function cat() {
    console.log('Meow!');
  }
}
Here, two constants are added to the Tools namespace from separate declarations.
Typescript
namespace Tools {
  export const hammer = 'Hammer';
}

namespace Tools {
  export const screwdriver = 'Screwdriver';
}
Sample Program

This program shows how two namespace declarations with the same name merge. Both hello and goodbye functions are available under Greetings.

Typescript
namespace Greetings {
  export function hello() {
    console.log('Hello!');
  }
}

namespace Greetings {
  export function goodbye() {
    console.log('Goodbye!');
  }
}

Greetings.hello();
Greetings.goodbye();
OutputSuccess
Important Notes

Declaration merging only works if the namespace names are exactly the same.

Use export inside namespaces to make functions or variables accessible outside.

Declaration merging helps keep code organized and easy to extend.

Summary

Declaration merging combines multiple namespace blocks with the same name into one.

This allows adding new members to a namespace in different places.

It helps organize and extend code without changing original namespace code.