Emmanuel Akinfulubi

TypeScriptModules and namespaces

Export a namespace to another file in TypeScript

8 Export a namespace and use it from another file

fair

Write a namespace holding a logging function, export the namespace, and import it into another file to log messages.

Stuck? Three hints, smallest first
  1. 1. A namespace can be exported from a module like anything else.
  2. 2. Mixing namespaces and modules is usually a sign you want just one of them.
  3. 3. The modern equivalent is a module of named exports, imported with import * as Logger.

The real answer, across 2 files. Type-checked by the compiler at build time; not runnable in a browser, because a panel cannot contain import or export.

logger.ts

// A namespace, exported from a module.
export namespace Logger {
  const lines: string[] = [];

  export function logMessage(message: string): void {
    lines.push(message);
  }

  export function history(): readonly string[] {
    return lines;
  }
}

consumer.ts

import { Logger } from './logger.js';

Logger.logMessage('bus departed');
Logger.logMessage('bus arrived');

for (const line of Logger.history()) console.log(line);

// The modern spelling of the same thing, with no namespace at all:
//   // logger2.ts
//   const lines: string[] = [];
//   export function logMessage(m: string): void { lines.push(m); }
//   export function history(): readonly string[] { return lines; }
//
//   // consumer2.ts
//   import * as Logger2 from './logger2.js';
//   Logger2.logMessage('same effect, one concept fewer');

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

// The namespace itself needs no import, so this part runs as written.
namespace Logger {
  // Private to the namespace: no export, so nothing outside can reach it.
  const lines: string[] = [];

  export function logMessage(message: string): void {
    lines.push(message);
  }

  export function history(): readonly string[] {
    return lines;
  }

  export function clear(): void {
    lines.length = 0;
  }
}

Logger.clear();
Logger.logMessage('bus departed');
Logger.logMessage('bus arrived');

for (const line of Logger.history()) console.log(line);

// Logger.lines;   // error: Property 'lines' does not exist on type 'typeof Logger'

test('two messages were kept', Logger.history().length, 2);
test('in order', Logger.history()[0], 'bus departed');
test('and the second', Logger.history()[1], 'bus arrived');
test('clear empties it', (() => { Logger.clear(); return Logger.history().length; })(), 0);
test('the array itself is not reachable from outside', 'lines' in Logger, false);

Output


      

The commented block in consumer.ts is the point of the exercise. A module of named exports imported as import * as Logger gives you the identical calling style, Logger.logMessage(...), with one concept fewer to explain. If you find yourself exporting a namespace from a module, you almost certainly wanted just the module.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.