Concept Flow - Namespace merging
Declare Namespace A
Declare Namespace A again
Compiler merges both
Use merged Namespace A
TypeScript merges multiple declarations of the same namespace into one combined namespace.
namespace A {
export const x = 1;
}
namespace A {
export const y = 2;
}
console.log(A.x, A.y);| Step | Action | Namespace State | Output |
|---|---|---|---|
| 1 | Declare namespace A with x=1 | A = { x: 1 } | |
| 2 | Declare namespace A again with y=2 | A = { x: 1, y: 2 } | |
| 3 | Access A.x and A.y | A unchanged | 1 2 |
| Namespace A | After 1 | After 2 | Final |
|---|---|---|---|
| Properties | { x: 1 } | { x: 1, y: 2 } | { x: 1, y: 2 } |
Namespace merging in TypeScript: - Multiple namespaces with the same name combine into one. - All exported members merge into a single namespace object. - Avoid exporting duplicate names to prevent compiler errors. - Use merged namespace by accessing combined members.
export.export function greet() inside the namespace.namespace Alpha {
export const value = 10;
}
namespace Alpha {
export function getValue() { return value * 2; }
}
console.log(Alpha.getValue());value and getValue are in the same namespace.getValue() returns value * 2, which is 10 * 2 = 20.namespace Beta {
export let count = 5;
}
namespace Beta {
let count = 10;
export function showCount() { return count; }
}
console.log(Beta.showCount());count without export, which shadows the exported count from the first namespace.showCount() returns the inner count (10), not the exported one (5), which may be unexpected.Utils defined in another file by adding a new exported function double that doubles a number. Which is the correct way to do this using namespace merging?Pass the test and this pattern moves unknown