0
0
Typescriptprogramming~5 mins

Namespace merging in Typescript

Choose your learning style9 modes available
Introduction

Namespace merging lets you combine multiple pieces of code with the same name into one. This helps organize code and add features without changing the original part.

You want to add new functions or variables to an existing namespace without rewriting it.
You have code split across files but want to group related parts under one name.
You want to extend third-party namespaces safely without modifying their source.
You want to keep your code organized by grouping related items under one namespace.
Syntax
Typescript
namespace MyNamespace {
  export function greet() {
    console.log('Hello');
  }
}

namespace MyNamespace {
  export function bye() {
    console.log('Goodbye');
  }
}

Each namespace block with the same name merges into one combined namespace.

Use export to make functions or variables accessible outside the namespace.

Examples
Two namespace blocks named Animals merge to hold both dog and cat functions.
Typescript
namespace Animals {
  export function dog() {
    console.log('Woof');
  }
}

namespace Animals {
  export function cat() {
    console.log('Meow');
  }
}
Constants hammer and screwdriver are combined under one Tools namespace.
Typescript
namespace Tools {
  export const hammer = 'Hammer';
}

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

This program shows two namespace blocks named Greetings. They merge so you can call both hello and goodbye functions from the same namespace.

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

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

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

Namespace merging only works with namespaces, not with modules or classes.

All merged parts must be in the same scope (like the same file or global scope) to merge correctly.

Use namespace merging carefully to avoid confusing code structure.

Summary

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

It helps organize and extend code without changing original parts.

Use export to share functions or variables outside the namespace.