Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript Namespaces vs Modules: Syntax, Declaration Merging, and Use Cases

How namespace merging works across files, why isolatedModules rejects it, and a migration path to ES modules with barrels and export * as.

~6 min readTypeScript
#TypeScript#Architecture#Modules
3D illustration contrasting legacy namespace domes with modern modular ES import/export pipelines

A namespace groups names under one global-ish object; a module is a file with its own scope and explicit imports and exports. Both can hold types, values, and nested members, and both compile to JavaScript that looks similar in a debugger — which is why the two are confused. The difference that matters is where the boundary sits: a namespace is a declaration that can merge across files and leaks into whatever scope declares it, while a module is a file the loader resolves and the bundler can analyze, split, and tree-shake.

Quick Summary

  • namespace N { export const x = 1 } emits an object (an IIFE assigning to N) and exposes only exported members.
  • A file with any top-level import or export is a module; everything else is a global script, and two scripts declaring the same name collide.
  • Namespace declarations with the same name merge across files, which was useful before modules and is now the main reason namespaces survive in hand-written ambient typings.
  • Under isolatedModules (implied by verbatimModuleSyntax), a global script is an error (TS1208), so a namespace file without an export no longer compiles.
  • import x = require("m") and export = are TypeScript's CommonJS syntax; both are rejected or warning-prone in ES module output.
  • export as namespace Lib plus declare namespace is how a UMD library describes its global variable in a .d.ts.
  • Modern replacement: one module per file, a barrel that re-exports, and export * as Types when a namespace-shaped object is genuinely wanted.
  • Namespaces are not dead: ambient declarations, global augmentation, and merged function/class/enum companions still use them.

Basic syntax and type signatures

typescript
// 2012-era style: one namespace, merged across files. namespace App { export interface User { id: string } export const version = "1.0.0"; export namespace Api { export function getUser(id: string): User { return { id }; } } } App.Api.getUser("1");
typescript
// Module style: one file, explicit exports. export interface User { id: string } export const version = "1.0.0"; export function getUser(id: string): User { return { id }; } // Importing a namespace-shaped object from a module. import * as App from "./app"; App.getUser("1");

The less common but still current forms:

typescript
// CommonJS interop written by hand. import fs = require("node:fs"); export = class Logger { log(msg: string) {} }; // Ambient namespace for a global library. declare namespace MyLib { function init(options: { el: string }): void; namespace Config { let debug: boolean } } declare const myLib: typeof MyLib; // UMD declaration. export as namespace MyLib; // the global variable name, in a .d.ts export = MyLib;

import * as App produces a namespace object at runtime only if the module has runtime exports; a module with only types gives an object the compiler erases. import type * as Types from "./types" is the form that guarantees erasure under verbatimModuleSyntax. The import x = require() syntax is not the same construct as a namespace — it is the CommonJS call spelled in type syntax — but it is the piece most often found next to one, because the namespaces that remain in the wild are usually attached to a CommonJS library.

Comparison of namespaces and ES modules

PropertynamespaceES module
Scopeglobal script, or the enclosing modulethe file
Emitted codeIIFE assigning an objectimport/export per loader
Cross-file mergeyes, by nameno; each file is its own module
Loadingload order in script tags, or outFile with AMD/Systemresolved by the loader or bundler
Tree-shakingeffectively noneper export
Lazy loadingnodynamic import()
Circular referencessilent, order-dependentdetected by the loader, partly tolerated
Ambient usestill the standard (declare namespace)declare module
Statuslegacy for application codethe default

The row that decides most migrations is the loading row. A namespace tree works only when every file is either concatenated (outFile, which requires module: "amd" | "system" and is not supported for ES output) or loaded by script tags in the right order. A bundler given ES modules can start from an entry point, build the graph, drop unused exports, and split chunks — none of which it can do with a set of IIFEs it must assume are order-dependent.

Practical edge cases and deep dives

1. Merging works only inside the same scope

typescript
// models/user.ts namespace Models { export interface User { id: string } } // models/post.ts namespace Models { export interface Post { id: string; author: Models.User } }

Without top-level imports or exports, both files are global scripts and the two Models declarations merge, so Models.Post can reference Models.User. Add a single import to either file and it becomes a module, the namespace is now module-scoped, and the merge silently stops: TS2503: Cannot find namespace 'Models' or a missing member. That is the failure mode of the style as a codebase grows — a refactor that adds an import to one file breaks a merge three directories away, with an error that points at the consumer.

Merging also works for a namespace plus a function, class, or enum of the same name, which is how static-like members are attached:

typescript
function parse(input: string): parse.Result { return { ok: true, value: input }; } namespace parse { export interface Result { ok: boolean; value: string } export const version = 1; }

The function and the namespace merge into one value with a type attached. TypeScript itself uses this pattern (export = with a namespace), and it is the one place where a namespace is the natural tool rather than a legacy habit.

2. export = and import = under ES module output

typescript
// legacy.d.ts declare function legacy(options: { debug?: boolean }): void; declare namespace legacy { const version: string; } export = legacy;
typescript
// consumer.ts, with esModuleInterop import legacy from "legacy"; legacy({ debug: true }); console.log(legacy.version);

export = describes a CommonJS module.exports = ..., and a consumer must either use import legacy = require("legacy") (which requires module: "commonjs" or similar, not esnext) or import legacy from "legacy" with esModuleInterop enabled. The friction is not cosmetic: under module: "esnext" with verbatimModuleSyntax, import = require is an error (TS1202: Import assignment cannot be used when targeting ECMAScript modules), and the default import only works because the compiler synthesizes the interop wrapper at emit. A library migrating to ESM needs a real export default plus named exports, and its .d.ts needs export default with no export =.

The error that gives this away in application code is TS1259: Module '"x"' can only be default-imported using the 'esModuleInterop' flag, which appears when a .d.ts says export = and the import is written as a default import without the flag.

3. Ambient namespaces are still the right tool

typescript
// types/analytics.d.ts declare namespace Analytics { interface Options { apiKey: string; batchSize?: number; } function init(options: Options): void; function track(event: string, props?: Record<string, unknown>): void; namespace internal { let queue: unknown[]; } } declare global { interface Window { analytics?: typeof Analytics; } } export {}; // makes this file a module so `declare global` is legal

An ambient namespace does not emit anything; it describes a global object that exists at runtime. Inside a .d.ts the namespace is the correct construct because a module declaration would say "this name is imported" when the library's actual API is a global. The export {} at the end is required for declare global (TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations), and it is the same trick used to turn a file with only types into a module without adding a runtime import.

4. Migrating a namespace tree to modules

typescript
// before: js/utils.ts (global script) namespace Utils { export function clamp(n: number, min: number, max: number): number { return Math.min(Math.max(n, min), max); } export interface Range { min: number; max: number } } // after: utils/clamp.ts export function clamp(n: number, min: number, max: number): number { return Math.min(Math.max(n, min), max); } export interface Range { min: number; max: number } // after: utils/index.ts (barrel) export * from "./clamp"; export * as Math from "./math"; // keeps the namespace-shaped object when needed

The migration is mechanical but has three traps. First, consumers that referenced Utils.clamp must change to import { clamp }, and any Utils.Range used in a type position must become import type { Range }. Second, a namespace member called default or new needs renaming, since those are reserved in import syntax. Third, side-effectful namespace initializers (code that ran when the namespace object was created) must move into an explicit init() or a module-level statement whose timing is now decided by the import graph rather than by script order.

A safe order is: convert leaf namespaces to modules while keeping a shim (export const Utils = { clamp }), update imports file by file, then delete the shim. The shim keeps both styles working during the migration, which matters in a codebase without a type checker in CI.

5. import type and type-only namespaces

typescript
import type * as Models from "./models"; // erased, never a runtime object import { type User, getUser } from "./models"; // mixed: type erased, value kept export type { User } from "./models"; // A namespace of types only, exported from a module. export namespace Shapes { export type Circle = { kind: "circle"; r: number }; export type Square = { kind: "square"; s: number }; }

import type * as Models is the module replacement for import Models = require("./models") when only types are needed, and it is required under verbatimModuleSyntax for imports that would otherwise be emitted. A namespace containing only types inside a module is legal, emits nothing, and is occasionally preferred for grouping — but export type { ... } and a plain barrel give the same ergonomics without the namespace syntax, and they work with isolatedModules where a namespace-only file can trip the global-script check.

Common mistakes and compiler errors

Error or symptomCauseFix
TS1208: 'file.ts' cannot be compiled under 'isolatedModules' because it is considered a global scripta file with no import/exportadd export {} or convert to a module
TS2503: Cannot find namespace 'X'the namespace is module-scoped, or the file is not includedexport/import it explicitly
TS2694: Namespace 'X' has no exported member 'Y'member not marked exportadd export, or fix the reference
Merge stops after adding an importthe file became a modulemove the shared types into an imported module
TS2309: An export assignment cannot be used in a module with other exported elementsexport = mixed with exportchoose one style; use export default
TS1202: Import assignment cannot be used when targeting ECMAScript modulesimport = require under module: esnextswitch to import ... from, or change module target
TS1259: can only be default-imported using 'esModuleInterop'export = in the declaration, default import in codeenable esModuleInterop or fix the import
TS2669: Augmentations for the global scope can only be directly nested in external modulesdeclare global in a script fileadd export {}
Namespace object is undefined at runtimeonly types were declared, or the file was not loadedcheck emit, use a module import
Two files declare the same global nameboth are scripts and the names collidemake them modules

The migration decision is not about style. Application code that ships through a bundler gains splitting, tree-shaking, and cycle detection from ES modules, and loses nothing that namespaces provided except a merged global name — which was the source of the problem in the first place. The places to keep namespaces are the places where nothing is loaded: .d.ts files describing a global script, UMD declarations, and the function-plus-namespace merge that attaches statics to a callable. Everywhere else, one file with export and a barrel is shorter, checkable, and supported by every tool in the chain.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.