What does TypeScript emit for `namespace App.Utils { const salt = 'x'; export const key = salt; }`, and for a types-only namespace?
answer
- a function that runs immediately
- reuse the object if it exists
- one wrapper per dotted level
- export becomes a property assignment
- no values, no output
basics
~20 sA dotted namespace with values compiles to a var plus nested immediately invoked functions, one per name level. Exports become properties on the object and unexported members stay local. A namespace holding only types emits nothing.
solid answer
~50 sIt compiles to a top-level `var App` and a function called immediately with `App || (App = {})`, with a second function inside for `Utils`, called with `Utils = App.Utils || (App.Utils = {})`. Inside, the unexported `salt` stays an ordinary local, while the exported `key` becomes the assignment `Utils.key = salt`, and every reference to an exported member is rewritten the same way. The `||` is what makes reopening work: a later block, even in another file, picks up the object that already exists. Each block has its own function, so an unexported member is invisible to the next block while an exported one is reachable as a property. Nothing protects you from load order, because these functions run when the script runs. A namespace holding only interfaces and type aliases emits no JavaScript, and using its name as a value is an error.
code
typescript · 5 linesnamespace App.Utils {
const salt = 'x';
export function hash(s: string) { return salt + s; }
export const v = hash('a');
}go deeper
Recall the outline: a variable, a function that runs immediately, and exports attached as properties. A namespace of only types leaves nothing behind.
Walk through the emit out loud: why the argument is App || (App = {}), how dotted names nest, and what rewriting export does to a reference.
Use the emit to explain production symptoms, such as code that type-checks and then fails at load because script order left a member unassigned.
Point out that the emit has no dependency graph at all, so order and reachability are invisible to tools, which is what a move to modules buys back.
## The shape of the output A TypeScript **namespace** that holds values compiles to a variable and an **immediately invoked function expression**, or IIFE: a function that is called as soon as it is defined. For a dotted name there is one such function per level. ```ts namespace App.Utils { const salt = 'x'; export const key = salt; } ``` With a modern `target`, the compiler emits this: ```js var App; (function (App) { var Utils; (function (Utils) { const salt = 'x'; Utils.key = salt; })(Utils = App.Utils || (App.Utils = {})); })(App || (App = {})); ``` ## Reading it from the outside in 1. `var App;` declares the name. In a script file, a file with no top-level `import` or `export`, that is a global variable. `var` can be declared repeatedly without error, which reopening relies on. 2. The outer function is called with `App || (App = {})`. If `App` already holds an object, that object is passed in. If not, a new one is created and stored. 3. The inner function does the same one level down, on `App.Utils`, and also stores the result in its local `Utils`. 4. The body runs at once, so its side effects happen at script load time. ## Exported and unexported members The rewriting of `export` is the core of the feature: - **An unexported member** stays a plain local inside the function. `salt` lives in that function's closure, and nothing outside can reach it. - **An exported member** becomes a property assignment, here `Utils.key = ...`. An exported function is declared locally and then assigned, as in `Utils.hash = hash`. - **A reference to an exported member** is rewritten too. Inside any block of the namespace, a bare `key` compiles to `Utils.key`. - **An exported `const`** is read-only only for the type checker. At runtime it is an ordinary writable property on an ordinary object. ## Reopened blocks and file order Two blocks with the same name share one object but not one function: ```ts namespace Animal { let haveMuscles = true; export let legs = 4; } namespace Animal { export function count() { return legs; } // emits Animal.legs // haveMuscles here would be a compile error } ``` The second block can use `legs` because the compiler knows it is exported and rewrites it to a property read. It cannot use `haveMuscles`, which is a local of a different function. The handbook's rule is the same: non-exported members are visible only in the original, un-merged namespace. Across files, `/// <reference path="..." />` tags tell the compiler how the files relate, and they let `outFile` order the concatenated output. They do nothing at runtime. With one output file per input, your script tags must load the files in the right order. Get that wrong and you see a runtime failure in code that type-checked: a `ReferenceError` if the namespace object does not exist yet, or a `TypeError` such as "is not a constructor" if it exists but that member has not been assigned. Reading a plain value member too early gives `undefined` with no error at all, which is the hardest of the three to spot. ## Types-only namespaces A namespace with only interfaces and type aliases has nothing to do at runtime, so the compiler emits nothing for it: ```ts namespace OnlyTypes { export interface Point { x: number } } let p: OnlyTypes.Point = { x: 1 }; // emits: let p = { x: 1 }; ``` Using it as a value, as in `console.log(OnlyTypes)`, fails with TS2708, "Cannot use namespace 'OnlyTypes' as a value". The handbook's declaration table lists a namespace as creating both a namespace meaning and a value; this case is the exception, because no value is ever created. ## Dotted and nested forms | Source | Result | |---|---| | `namespace A.B { }` | `B` is reachable as `A.B` | | `namespace A { export namespace B { } }` | the same object structure | | `namespace A { namespace B { } }` | `B` is private to the block, with no `A.B` | The dotted form exports each inner level for you. The nested form needs its own `export`. Inside a module file the outer variable is scoped to the module instead of being global, and `export namespace X` emits `export var X`.
- Why can a second `namespace Animal` block read an exported `legs` from the first block but not an unexported `haveMuscles`?Each block compiles to its own function. An unexported `haveMuscles` is a local of the first function, so the second has no scope access to it and the compiler reports an error. An exported `legs` is a property of the shared object, and the compiler rewrites the bare name to `Animal.legs`, so it resolves.
- A TypeScript namespace split across files uses `/// <reference path>` tags and type-checks, yet throws at load. What do those tags fix, and what do they not fix?The tags tell the compiler how the files relate, and with `outFile` the compiler orders the concatenated output by them. With per-file output they change nothing at runtime, so your script tags must still load the files in dependency order. A wrong order leaves the object or member missing when a block runs.
- In TypeScript, is `namespace A.B {}` different from `namespace A { namespace B {} }`?Yes, because the second form does not export `B`. The dotted form exports each inner level for you, so it matches `namespace A { export namespace B {} }` and `A.B` is reachable. Without `export`, `B` is private to the enclosing block.
Think of a shared ring binder on a common shelf. Each block looks for the binder, creates it only if it is missing, and clips in the pages it exports, while loose notes leave with that block's author. Read a page before its block has run and it is not there yet.
- A namespace compiles to a class with static members.
- Reference tags make the runtime load namespace files in the right order.
- Every namespace emits a wrapper function, even one holding only interfaces.
- A second block of the same namespace can see the first block's unexported variables.
- An exported const in a namespace is frozen at runtime.