0
0
Typescriptprogramming~10 mins

Namespace merging in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Typescript
namespace A {
  export const x = 1;
}
namespace A {
  export const y = 2;
}
console.log(A.x, A.y);
This code shows two namespace declarations with the same name 'A' that merge into one namespace with both x and y.
Execution Table
StepActionNamespace StateOutput
1Declare namespace A with x=1A = { x: 1 }
2Declare namespace A again with y=2A = { x: 1, y: 2 }
3Access A.x and A.yA unchanged1 2
💡 All declarations merged; output shows both properties.
Variable Tracker
Namespace AAfter 1After 2Final
Properties{ x: 1 }{ x: 1, y: 2 }{ x: 1, y: 2 }
Key Moments - 2 Insights
Why can we declare the same namespace name twice?
TypeScript merges the contents of namespaces with the same name into one combined namespace, as shown in steps 1 and 2 of the execution_table.
What happens if both namespaces export the same name?
If both namespaces export the same name, it causes a compiler error due to duplicate identifier. This example avoids that by using different names (x and y).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of namespace A after step 2?
A{ x: 1, y: 2 }
B{ x: 1 }
C{ y: 2 }
D{}
💡 Hint
Check the 'Namespace State' column in row 2 of execution_table.
At which step does the output '1 2' appear?
AStep 1
BStep 2
CStep 3
DNo output
💡 Hint
Look at the 'Output' column in execution_table rows.
If the second namespace also exported 'x', what would happen?
AThe second x would overwrite the first
BCompiler error due to duplicate export
CBoth x values would exist separately
DNamespace merging would ignore the second x
💡 Hint
TypeScript checks for duplicate identifiers in merged namespaces.
Concept Snapshot
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.
Full Transcript
This example shows how TypeScript merges multiple declarations of the same namespace name into one combined namespace. First, namespace A is declared with a property x=1. Then, namespace A is declared again with a property y=2. The compiler merges these so that namespace A contains both x and y. When accessing A.x and A.y, the output is '1 2'. This merging allows splitting namespace code across multiple blocks. However, exporting the same name twice causes a compiler error due to duplicate identifier.