In modern TypeScript, when is a `namespace` still the right tool, and what does `export as namespace` do in a library's typings?
answer
- a global loaded by script tag
- describes, emits nothing
- dotted names for types and values
- the file works as module and global
- a module file must opt in
basics
~20 sA namespace still fits typings for a library exposing a global object, where declare namespace describes that object and emits nothing. In a declaration file, export as namespace says a module's exports also exist under a global name.
solid answer
~50 sIts main remaining job is describing code that already exists. A library loaded by a script tag exposes a global object, and `declare namespace ChartLib { ... }` gives the compiler its shape, including named types such as `ChartLib.Options`, which a plain `declare const` cannot provide. It emits no JavaScript, so it costs nothing at runtime. `export as namespace MathLib;` is for a library that works both ways, usually called UMD. Placed in a module-shaped declaration file, it says the file's exports also exist as the global `MathLib` when loaded as a script. It is legal only in declaration files. Script files can use that global directly, while a module file gets error TS2686 unless it imports the library or sets `allowUmdGlobalAccess`. What it is not right for is new application code with runtime members, or wrapping a module's exports, where the file already groups them.
code
typescript · 7 linesdeclare namespace ChartLib {
interface Options { width: number }
function draw(options: Options): void;
}
const opts: ChartLib.Options = { width: 400 };
ChartLib.draw(opts);go deeper
Recall that namespaces survive mainly in typings for libraries with a global object, and that declare means nothing is generated.
Explain why a namespace rather than a typed constant: named types under a dotted name. Then explain what export as namespace adds for UMD libraries.
Reject value namespaces and needless wrappers in review while leaving correct global typings alone, and treat a module reading a UMD global as a hidden dependency.
Set a simple standard: namespaces may describe what already exists at runtime but may not generate new code, then enforce it with tooling.
## The job that is left A TypeScript **namespace** with runtime code has been overtaken by ES modules, but the other half of the feature still has a purpose. A namespace can describe a shape without producing code. That suits one situation very well: a JavaScript library that is loaded by a script tag and exposes a single global object. The handbook makes the same point: most such libraries expose only a few top-level objects, and namespaces are a good way to represent them. ## Describing a global object The `declare` keyword says the thing exists and that the compiler should not generate it: ```ts declare namespace ChartLib { interface Options { width: number; } function draw(options: Options): void; } ChartLib.draw({ width: 400 }); ``` Why a namespace and not a typed constant? In TypeScript, a declaration can create a **value**, a **type** or a **namespace** meaning, and a dotted type name needs the namespace meaning. Compare the alternative: ```ts declare const ChartLib: { draw(): void }; let o: ChartLib.Options; // TS2503: Cannot find namespace 'ChartLib' ``` A namespace carries both the runtime members and the named types under one dotted name, which is how a library's users expect to write them. Which file such a declaration lives in, and how the compiler finds it, is a separate subject; the point here is the shape it gives you. ## Exposing a module as a global **UMD**, or Universal Module Definition, is a packaging style in which one JavaScript file works two ways: imported as a module, or loaded by a script tag, where it creates a global. `export as namespace` is the typings for that second path. ```ts // math-lib/index.d.ts export as namespace MathLib; export function add(a: number, b: number): number; ``` The rules follow from what it describes: - **Declaration files only.** In a `.ts` file it is error TS1315, because it describes a global the compiler is not going to create. - **Script files** can write `MathLib.add(1, 2)` once the declaration is in the program. - **Module files** get TS2686, "'MathLib' refers to a UMD global, but the current file is a module. Consider adding an import instead." - **`allowUmdGlobalAccess`** lifts that error for module files, for the case where a page really does load the global separately. The error is useful. A module that quietly reads a global has a dependency nobody can see, and the import is usually what you meant. ## Forms compared | Form | Emits JavaScript? | Reasonable today? | |---|---|---| | `declare namespace X { ... }` | no | yes, for a library's global object | | `export as namespace X;` | no | yes, for a UMD library's typings | | `namespace X { export type T = ... }` | no | sometimes, to group types | | `namespace X { export const y = 1 }` | yes | only in legacy code | | `export namespace X { ... }` in a module | yes, if it holds values | no, it is needless nesting | The first three rows leave no JavaScript behind, so they cannot introduce a load-order problem. The `namespace X` row with values is where that risk, and the generated wrapper, comes back. ## Grouping types in application code A types-only namespace is harmless at runtime, and it gives a tidy qualified name such as `Api.User`. A module does the same job with `import type * as Api from './api'`, which also leaves no trace in the output, so it is the more common choice in module code. ## Where it is the wrong tool Two patterns come up often in code review: 1. **A new application namespace with runtime members.** This brings back hidden dependencies and load-order problems, and tools that only strip types will refuse it. 2. **A namespace wrapping a module's exports.** The handbook calls this needless namespacing. With `export namespace Shapes { export class Triangle {} }` in `shapes.ts`, consumers end up writing `shapes.Shapes.Triangle`. The file already groups its exports, and the importer already picks the name. A good test: is this block describing something that already exists at runtime, or generating something new? Describing is the job namespaces still do well. Generating is the job modules took over.
- Why not describe a TypeScript library's global with `declare const ChartLib: { draw(): void }` instead of a namespace?That types the value, but it creates no namespace meaning, so `ChartLib.Options` fails with TS2503, "Cannot find namespace". The handbook's own example splits the two: a namespace of types plus a `declare var` typed with one of them. A namespace with members puts both under one dotted name.
- Should application code in a module-based TypeScript project group its types in a namespace?It works and emits nothing, but it is usually unnecessary. Put the types in a module and write `import type * as Api from './api'`, which gives the same `Api.User` qualified name. The importer picks the name, and no second grouping has to be maintained inside the file.
- Namespaces are obsolete, so no modern TypeScript typings should use them.
- A declare namespace block generates the global object at runtime.
- Writing export as namespace makes the compiler emit a UMD wrapper.
- Any module file can read a UMD global without an import or a flag.
- Every module should wrap its exports in a namespace to avoid name collisions.