0
0
Typescriptprogramming~5 mins

Declaration merging for namespaces in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Declaration merging for namespaces
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
22 function calls
1010 function calls
100100 function calls

Pattern observation: The execution grows linearly with the number of functions called, not with how many namespace parts exist.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly with how many functions you call from the merged namespace.

Common Mistake

[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.

Interview Connect

Understanding how declaration merging works helps you explain how TypeScript organizes code without slowing down your program.

Self-Check

"What if we added many nested namespaces inside the merged namespace? How would that affect the time complexity?"