In TypeScript, what does merging a `namespace` into a function, class or enum leave at runtime, and what traps follow?
answer
- the wrapper's argument is already truthy
- properties land on the existing value
- static-like, but assigned later
- enum objects get extra entries
basics
~20 sA merge leaves one value: the function, class or enum itself, carrying the exported members as properties. On a class they are assigned after the class body; on an enum they join its keys, which breaks iteration.
solid answer
~50 sOne value remains: the function, class or enum itself, with exported members added as properties. Take `function label() {}` followed by `namespace label { export let prefix = 'Hi'; }`. The wrapper is still called with `label || (label = {})`, but `label` already holds a function, which is truthy, so no new object appears and `label.prefix = 'Hi'` lands on the function. Unexported members stay locals of the wrapper. A class works the same way, giving static-like properties and inner classes such as `Album.AlbumLabel`, but the wrapper runs after the class body, so a static initializer reading that member sees `undefined`. An enum is an object too, so a merged function joins its entries: `Object.keys(Color)` and `keyof typeof Color` now include it, which breaks code looping over the enum. A merged namespace holding only types emits nothing.
code
typescript · 8 linesenum Color { red = 1 }
namespace Color {
export function mix() { return Color.red; }
}
console.log(Object.keys(Color)); // [ '1', 'red', 'mix' ]
const k: keyof typeof Color = 'mix'; // compilesgo deeper
Recall that a namespace can add properties to a function, class or enum of the same name, and that callers then reach them with a dot.
Explain the merge through the emit: the wrapper's argument already holds the value, so exports are assigned onto it, and only exports.
Watch for the runtime traps, namely static initializers that run before the wrapper and enum loops that suddenly meet a function.
Judge whether a merge earns its place at all, given that plain statics and module functions do the same job without generated code.
## One value, not two TypeScript lets a **namespace** share a name with a function, class or enum declared before it. Both declarations describe a single entity. The type checker sees the combined shape, and at runtime there is one value with extra properties. The reason is visible in the emit. A namespace with values compiles to a function called immediately, with `name || (name = {})` as its argument. Normally `name` is empty and a new object is created. In a merge, `name` already holds something truthy, so that existing value is passed in and the exports are assigned onto it. ```ts function label(name: string) { return label.prefix + name; } namespace label { export let prefix = 'Hi '; } ``` ```js function label(name) { return label.prefix + name; } (function (label) { label.prefix = 'Hi '; })(label || (label = {})); ``` No second `var` appears, because the function declaration already created the name. Only exported members land on the value. An unexported member stays a local of the wrapper, and the merged function cannot read it either. ## The three merges compared | Merged with | What the exports become | Runtime trap | |---|---|---| | Function | properties on the function object | none beyond assignment order | | Class | static-like properties on the class | assigned after the class body finishes | | Enum | extra entries on the enum object | enumerating the enum picks them up | The handbook describes the merge rules along with the rest of declaration merging, including the requirement that the namespace follow the declaration it merges with. What matters here is the runtime result. ## Merging with a class This is the classic way to model an inner class: ```ts class Album { label!: Album.AlbumLabel; } namespace Album { export class AlbumLabel {} } ``` This gives you three things: - **A type:** `Album.AlbumLabel` can annotate fields, as `label` does above. - **A value:** `new Album.AlbumLabel()` works once the wrapper has run. - **Extra statics:** the handbook also uses this form to add more static members to an existing class. The emit is the class first, then the wrapper, so the assignment happens later. A **static initializer** runs while the class is being defined, which is before the wrapper. A `static` field that reads `Album.AlbumLabel` therefore gets `undefined`, and any code running during that window sees the same. ## Merging with an enum An enum compiles to an object, so a merged function is added to it as one more property: ```ts enum Color { red = 1, green = 2 } namespace Color { export function mix() { return Color.red + Color.green; } } Object.keys(Color); // ['1', '2', 'red', 'green', 'mix'] Object.values(Color); // ['red', 'green', 1, 2, [Function: mix]] ``` Two things change as a result: - **Runtime iteration.** Anything that loops over the enum to build a dropdown or validate a value now meets a function. - **The type side.** `keyof typeof Color` includes `'mix'`, so a helper that accepts any key of the enum accepts it as well. ## When nothing is emitted If the merged namespace holds only types, there is no wrapper at all: ```ts class Report { id = 1 } namespace Report { export type Id = string; } ``` `Report.Id` becomes a usable type, and the JavaScript contains only the class. This form is the cheap one: it adds a qualified type name and leaves the value alone. ## What to write instead in module code A merge is rarely needed in new code, and a merge with runtime code cannot run under a tool that only strips types: 1. For a class, write real `static` members or a separately exported class. 2. For a function, assign properties directly with `label.prefix = 'Hi '`. TypeScript recognizes property assignments on a function declaration in the same scope and types them. 3. For an enum, export a plain function beside it, such as `mixColor`, which leaves the enum's entries untouched. Reading the merge as "the namespace adds properties to a value that already exists" predicts all of the behaviour above, from the missing second `var` to the extra enum key.
- Does a TypeScript function merged with a namespace create a second object at runtime?No. The wrapper receives `label || (label = {})`, and because the function is already truthy the `{}` branch never runs. Exported members are assigned directly onto the function object, so `Object.keys(label)` lists them and there is still only one value bound to the name.
- Can a merged TypeScript function read an unexported member of its namespace?No. The unexported member is a local of the wrapper function, and the merged function is declared outside that wrapper. The handbook gives the same rule for classes: a member must be exported for the merged declaration to see it.
- Merging a function with a namespace creates a separate object beside the function.
- Unexported namespace members become private fields of the merged class.
- A static initializer can safely read a member added by a merged namespace.
- Adding a function to an enum through a namespace does not affect iterating over it.
- A merged namespace's members are copied onto the value only when first accessed.