Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 96 ยท Modules and Declarations

Namespaces

Learn TypeScript namespaces - syntax, nested namespaces, aliases, what they compile to, declaration merging, and why ES modules replaced them in modern code.

Before JavaScript had a standard module system, TypeScript gave developers its own way to group related code under one name: the namespace. A namespace is a named block whose exported members become properties of a single object, so Geometry.area() and Billing.area() can live side by side without clashing. TypeScript originally called them "internal modules".

Today, ES modules do that job better, and new application code almost never uses namespaces. You still need to understand them, though. They appear all over declaration files (NodeJS.ProcessEnv, Express.Request, JSX.IntrinsicElements), in older codebases, and in a few merging tricks that have no other syntax. This lesson covers how namespaces work, what they compile to, and how to recognize the cases where they still make sense.

Declaring a namespace

The namespace keyword opens a block. Inside it you write ordinary declarations. Only the ones marked export are visible from outside; everything else stays private to the block:

TypeScript A first namespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice three things:

  • You reach members with a dot: Geometry.area(...). Types are reached the same way: Geometry.Circle.
  • Object.keys(Geometry) prints [ 'circumference', 'area' ]. The namespace is a real object at runtime, holding the exported values. The interface isn't there, because types are erased.
  • TAU is missing from the list. Non-exported members are ordinary local variables inside the block.

Trying to read a non-exported member is a type error. The next example fails on purpose:

TypeScript Private namespace members (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler stops with main.ts(7,20): error TS2339: Property 'apiKey' does not exist on type 'typeof Config'. and nothing runs. The type name in the message, typeof Config, is a hint about how TypeScript sees a namespace: as a value whose type lists only the exports.

What a namespace compiles to

Namespaces are one of the few TypeScript features that generate code. The compiler turns the block into an immediately invoked function that fills in an object. The first example compiles to roughly this JavaScript:

JavaScript
var Geometry;
(function (Geometry) {
    const TAU = Math.PI * 2;
    function circumference(circle) {
        return TAU * circle.radius;
    }
    Geometry.circumference = circumference;
    function area(circle) {
        return Math.PI * circle.radius ** 2;
    }
    Geometry.area = area;
})(Geometry || (Geometry = {}));

The pattern Geometry || (Geometry = {}) is the key to namespaces. If an object named Geometry already exists, the function adds to it; otherwise it creates one. That is how a namespace can be split across several blocks (or several files) that all add members to the same object.

Because a namespace produces runtime code, it is not erasable syntax. Node's built-in type stripping (node main.ts) can only delete type annotations, so it rejects namespaces that contain values, and so does the --erasableSyntaxOnly flag described in the tsconfig lesson. With that flag on, the namespace above fails with error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled. Namespaces that contain only types are fine, since they leave nothing behind.

Old code sometimes writes module Geometry { ... } instead of namespace Geometry { ... }. The two meant the same thing, which confused everyone once ES modules arrived. TypeScript 7 rejects the old spelling with error TS1540: A 'namespace' declaration should not be declared using the 'module' keyword. Change the keyword to namespace. (declare module 'some-package' with a quoted name is different: it describes a real module, as you'll see in declaration files.)

Nested namespaces and aliases

Namespaces can nest, either with blocks inside blocks or with the dotted shorthand namespace A.B { }. Deep names get long, so TypeScript offers an alias syntax, import Short = Long.Path;, that works for both values and types:

TypeScript Nesting and import aliases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

namespace App.Models { } is shorthand for namespace App { export namespace Models { } }. The two dotted declarations both add to the same App object, which is why Object.keys(App) lists [ 'Models', 'Validation' ].

The import X = Y.Z form is not an ES import. It doesn't load a file; it just creates a local name for something already in scope. It compiles to a plain assignment, var Models = App.Models;. You'll occasionally see a related form, import fs = require('fs'), in old CommonJS-era TypeScript. Modern code uses import ... from instead (see Modules).

Namespaces across files (and why that stopped working)

In the pre-module era, a large project was split into many files that each added to one global namespace, glued together with triple-slash references and a single concatenated output file:

TypeScript
// shapes/circle.ts
/// <reference path="./base.ts" />
namespace Shapes {
  export class Circle extends Base { /* ... */ }
}
Terminal
# Old build: concatenate everything into one script (removed in TypeScript 7)
tsc --outFile dist/app.js

This setup had real problems: file order mattered, everything shared one global scope, bundlers couldn't remove unused code, and tools had to understand TypeScript-only syntax. The outFile option was deprecated in TypeScript 6.0 and removed in 7.0, so this style is now truly legacy. If you inherit such a project, migrating it to modules (one export per file, import where needed) is usually the first step of any upgrade.

Declaration merging with namespaces

The most useful thing namespaces still do is merge with other declarations of the same name. Because a namespace compiles to "add properties to an existing object", it can attach extra members to a function, a class or an enum.

Function + namespace: callable objects with properties

Some JavaScript APIs are a function that also carries properties (think of a format() function with format.defaults). A namespace with the same name as the function describes exactly that shape:

TypeScript Attaching properties to a function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The function must come first, because the namespace's compiled code adds properties to it. Modern TypeScript can also type this pattern without a namespace: plain assignments like formatPrice.symbol = '$'; right after a function declaration are recognized as "expando" properties. Both forms type-check; the namespace form is what you'll see in declaration files.

Class + namespace and enum + namespace

Merging with a class adds static-like members and lets you nest related types under the class name. Merging with an enum gives the enum helper functions, something enums can't have on their own:

TypeScript Merging with a class and an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

For classes, a static member is usually the clearer choice today (static fromFahrenheit(...)). The namespace form is still handy for nesting types under the class name, like Temperature.Scale, which static cannot do.

Type-only namespaces: where you still meet them

A namespace that contains only types (interfaces, type aliases, nested type-only namespaces) produces no JavaScript at all. That makes it a convenient way to group types under one name, and it is completely allowed under --erasableSyntaxOnly. Declaration files lean on this heavily. Node's types, for example, define NodeJS.ProcessEnv, the type of process.env, and our editor includes them:

TypeScript Using a type-only namespace from Node's types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Uncomment the last line and the compiler refuses with error TS2708: Cannot use namespace 'Api' as a value. That's the proof that Api is purely a compile-time name: it contains only types, so TypeScript emits no object for it. Compare that with Geometry in the first example, which became a real object.

Here are the places you will realistically meet namespaces:

Where Example Still a good idea?
Declaration files for global libraries declare namespace NodeJS { ... }, declare namespace Express { ... } Yes, this is the standard way to describe them
Augmenting a library's types declare global { namespace Express { interface Request { user?: User } } } Yes, see declaration files
JSX type definitions namespace JSX { interface IntrinsicElements { ... } } Yes, the compiler looks it up by name
Grouping types inside one module export namespace Api { export type ... } Acceptable, though separate exports are simpler
Organizing runtime code namespace Utils { export function ... } No, use modules

Namespaces versus modules

If you are writing new code, use modules. The reasons are practical:

  • Modules are standard JavaScript. Browsers, Node, Deno and every bundler understand import and export. Namespaces only exist in TypeScript.
  • Modules are erasable. Tools like Node's type stripping, esbuild and swc remove types without understanding TypeScript semantics. Value namespaces need real code generation.
  • Modules tree-shake. A bundler can drop unused exports from a module. A namespace is one object, so using one member keeps them all.
  • Modules have explicit dependencies. Every file says what it imports, so there's no hidden ordering and no shared global scope.

A module already acts like a namespace: import * as Geometry from './geometry.js' gives you Geometry.area() with the same dotted feel. Wrapping a module's contents in an extra export namespace adds nothing but nesting.

Migrating a namespace to modules is mechanical: move each namespace into its own file, keep the export keywords, delete the namespace X { wrapper, and replace X.member uses in other files with import * as X from './x.js' (or named imports). Merged helpers like Weekday.isWeekend become ordinary exported functions next to the enum, or a union type with a helper object.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A namespace Shop exports total() and declares const taxRate = 0.2; without export. What does Object.keys(Shop) print at runtime?

    A namespace with values compiles to a real object, but only exported members are assigned to it. taxRate is a local variable inside the generated function.
  2. 2. Does namespace Shapes { export interface Square { side: number } } produce any JavaScript?

    Type-only namespaces leave nothing behind, which is also why they are allowed under erasableSyntaxOnly and are common in declaration files.
  3. 3. Why does Node's built-in type stripping reject a namespace that exports a function?

    Type stripping can only remove type syntax. A value namespace has to be rewritten into an IIFE that builds an object, so it is not erasable syntax.
  4. 4. What does import Models = App.Models; do?

    The import-equals form with a dotted name is just an alias for something already in scope. It does not load any file.
  5. 5. You need to add a user property to Express's Request type in your app. Which tool fits best?

    Express declares its request type inside a global namespace, so interface merging inside declare global with namespace Express is the standard way to extend it.

Summary

  • A namespace groups declarations under one name; only exported members are visible outside, and you reach them with dots (Geometry.area, Geometry.Circle).
  • A namespace that contains values compiles to an IIFE that fills an object, so it is not erasable: Node type stripping and --erasableSyntaxOnly reject it. Type-only namespaces emit nothing.
  • namespace A.B { } nests; import Short = A.B; creates a local alias. The old module X { } spelling is an error in TypeScript 7.
  • Namespaces merge with functions, classes and enums to attach properties or helpers, and with each other across blocks.
  • Multi-file namespaces built with outFile are legacy; outFile was removed in TypeScript 7.
  • You still meet namespaces in declaration files (NodeJS, Express, JSX) and type augmentation. For organizing your own code, use ES modules.

Next: Migrating JavaScript to TypeScript