Declaration merging for namespaces in Typescript - Time & Space Complexity
We want to understand how the time it takes to run code changes when using declaration merging with namespaces in TypeScript.
Specifically, how does combining multiple namespace parts affect the work the program does?
Analyze the time complexity of the following code snippet.
namespace Shapes {
export function area(radius: number) {
return Math.PI * radius * radius;
}
}
namespace Shapes {
export function circumference(radius: number) {
return 2 * Math.PI * radius;
}
}
const r = 5;
console.log(Shapes.area(r));
console.log(Shapes.circumference(r));
This code shows two parts of the same namespace merged together, each adding a function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling functions inside the merged namespace.
- How many times: Each function is called once here, so constant time.
Since the namespace merging happens at compile time, the runtime cost depends on how many functions are called.
| Input Size (number of functions) | Approx. Operations |
|---|---|
| 2 | 2 function calls |
| 10 | 10 function calls |
| 100 | 100 function calls |
Pattern observation: The execution grows linearly with the number of functions called, not with how many namespace parts exist.
Time Complexity: O(n)
This means the time grows directly with how many functions you call from the merged namespace.
[X] Wrong: "Merging namespaces makes the program slower because it combines code at runtime."
[OK] Correct: Namespace merging happens before running the program, so it does not add runtime overhead by itself.
Understanding how declaration merging works helps you explain how TypeScript organizes code without slowing down your program.
"What if we added many nested namespaces inside the merged namespace? How would that affect the time complexity?"