Answer
Following from the docs on Multi-file namespaces.
...Even though the files are separate, they can each contribute to the same namespace and can be consumed as if they were all defined in one place. Because there are dependencies between files, we’ll add reference tags to tell the compiler about the relationships between the files. Our test code is otherwise unchanged.
So we need to apply a reference tag in order to let the compiler know that b.ts
is dependent on knowing the contents of a.ts
first.
b.ts
:
/// <reference path="a.ts" />
namespace aaa {
export const B = A + 1;
}
Notice how there is no export
! This is on purpose, this is because this will pollute the global scope with aaa
.
You cannot use a reference tag with an exported namespace, because by the very existence of the export
keyword it becomes a module, and a module will add create it's own scope, so if it is present the two aaa
's are now distinctly scoped.
There are ways to go about it without polluting your global scope, (and you've already discovered that way).
Don't use Namespaces and Modules
The TypeScript docs doesn't recommend using both modules and namespaces. Namespaces has been the old way to do logical naming to prevent name collisions before modern JS/TS. Modules have since taken over that role, and to use both in one file... a headache.
It is also worth noting that, for Node.js applications, modules are the default and we recommended modules over namespaces in modern code.
If it is for the sake of simply organizing code there is a topic on it: Needless Namespacing
A key feature of modules in TypeScript is that two different modules will never contribute names to the same scope. Because the consumer of a module decides what name to assign it, there’s no need to proactively wrap up the exported symbols in a namespace.
There is also an excellent description of it all in this answer to the question: How do I use namespaces with TypeScript external modules? Which will do a much better job explaining it all and is a highly recommended read.