Namespaces: the legacy module system
Why TypeScript has namespaces, what they compile to, why ES modules replaced them, and where they still appear in global declaration files.
Namespaces: the legacy module system
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Namespaces date from before JavaScript had a standard module system. They group code under one global name so separate scripts sharing one global scope don't collide.
- A namespace with values compiles to an object built by an immediately invoked function. Only members marked `export` become properties of that object.
- ES modules do the same job with file scope and explicit imports, and bundlers can drop unused exports from them, so new application code should use modules, not namespaces.
- A namespace containing values generates JavaScript, so it isn't erasable syntax. `erasableSyntaxOnly` reports it, and Node's type stripping refuses it.
- Namespaces still matter in declaration files: `declare namespace` describes globals, and merging into one, as with `NodeJS.ProcessEnv`, is how you extend a library's global types.
Before modules, everything was global
In 2012, when TypeScript appeared, browsers had no module system. A page loaded a list of <script> tags, and every top-level declaration in every file landed in the same global scope. If charts.js and forms.js both defined format(), whichever loaded last won.
The common fix was to put each library’s code inside one object and expose only that object, the module pattern covered in IIFEs and the module pattern. TypeScript gave that pattern its own syntax. At first it was called an “internal module” and written with module. It was renamed namespace once ES modules arrived and the two kinds of “module” became confusing.
What a namespace is
namespace Geometry {
export interface Point {
x: number;
y: number;
}
export function distance(a: Point, b: Point): number {
return Math.hypot(b.x - a.x, b.y - a.y);
}
const origin: Point = { x: 0, y: 0 }; // not exported: private to the namespace
export function fromOrigin(p: Point): number {
return distance(origin, p);
}
}
const d: number = Geometry.fromOrigin({ x: 3, y: 4 }); // 5
Inside the braces, code can use its own names freely. Outside, you only see what’s marked export, reached through Geometry.. Types work the same way, so Geometry.Point is usable as a type anywhere.
The compiled output is the module pattern written for you:
var Geometry;
(function (Geometry) {
function distance(a, b) {
return Math.hypot(b.x - a.x, b.y - a.y);
}
Geometry.distance = distance;
const origin = { x: 0, y: 0 };
function fromOrigin(p) {
return distance(origin, p);
}
Geometry.fromOrigin = fromOrigin;
})(Geometry || (Geometry = {}));
That last line is the interesting part. Geometry || (Geometry = {}) reuses the object if it already exists. A namespace can be split across several files, each adding to the same object, and the compiler merges their types too. Projects built this way linked the files with /// <reference path="..." /> comments and concatenated them into one script in the right order.
Why modules replaced them
ES modules solve the same problem with less machinery. Each file has its own scope by default. Dependencies are listed in import statements instead of implied by script order. Bundlers can see exactly which exports are used and drop the rest. A namespace is one object, so if you use one function from it, the whole object usually ships.
Namespaces also conflict with how TypeScript is run today. A namespace with values in it generates code, as the output above shows. That makes it non-erasable, in the sense covered in running TypeScript without a build step: Node’s type stripping rejects it, and erasableSyntaxOnly flags it:
error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
A namespace holding only types is fine, since there’s nothing to generate. TypeScript 6.0 also turned the old spelling, module Geometry { ... }, into an error, so namespace is the only keyword for these now.
For new application code the advice is simple: one file, one module, explicit import and export. If you want a single name to group related exports, import * as Geometry from "./geometry.js" gives you the same Geometry.distance call style with none of the downsides.
Where they still show up
You’ll still meet namespaces, mostly in declaration files that describe globals. A .d.ts file uses declare namespace to say “an object with these members exists at runtime” without generating anything. Some libraries also group their global types this way. @types/node puts several under a NodeJS namespace, and because namespaces merge, you can add to them from your own code:
// env.d.ts
declare namespace NodeJS {
interface ProcessEnv {
DATABASE_URL: string;
LOG_LEVEL?: "debug" | "info" | "warn";
}
}
With @types/node loaded, process.env.DATABASE_URL is now typed as string everywhere. The same merging attaches properties to a function or class of the same name, which is covered in declaration merging. Older codebases and some JSX setups also still use a global JSX namespace for element types.
So: read namespaces, don’t write new ones with runtime values. A declare namespace in a .d.ts file is still the right tool when you are describing or extending global types.
What the video covers
Nicos Tsourektsidis frames namespaces the way this lesson does, as something you should understand rather than reach for. Across 33 minutes it covers what a namespace is, merging, splitting a namespace across files, triple-slash reference directives, nested and ambient namespaces, and finally namespaces versus modules at 29:21. Use the chapters to skip around. The last section is the one to watch if you’re short on time. It was recorded in 2023, before erasableSyntaxOnly and before TypeScript 6.0 made the module keyword an error, so those two points come from the sections above.
Check yourself
What problem did namespaces solve when TypeScript introduced them?
Browser scripts all shared one global scope, so two files declaring a function with the same name would overwrite each other. A namespace puts a file's declarations inside one named object, so only that one name is global.
Why does Node's type stripping reject `namespace Config { export const port = 3000; }` but accept a namespace containing only interfaces?
The first produces a real JavaScript object holding `port`, so removing the text would delete behavior. A namespace with only types has nothing to emit and disappears entirely, so it is still erasable.
If namespaces are legacy, why do you still see `declare namespace NodeJS` in real projects?
`@types/node` groups some of its global types inside a `NodeJS` namespace. Declaring that namespace again in your own `.d.ts` file merges with it, which is how projects add their environment variables to `ProcessEnv`. Being `declare`d, it only describes types and emits nothing.
Why does TypeScript 6.0 reject `module Utils { export const x = 1; }`?
`module` was the original keyword for what TypeScript now calls namespaces. It was confusing next to ES modules, so the `namespace` keyword replaced it, and TypeScript 6.0 makes the old spelling an error. The `module` keyword now only appears in `declare module "name"` declarations.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.