← TypeScript

Patterns & principles · 1 of 10 · 13 min read

The Module pattern

Encapsulation in TypeScript — an ES module with a declared public interface, why namespace is the obsolete version of the same idea, and where #private fits.

  • Design patterns

The Module pattern is “public surface, private internals”. JavaScript needed a closure to express that; ES modules made it syntax; and TypeScript adds the part neither had — a declared public interface that the compiler holds the implementation to.

The modern form

// counter.ts
export interface Counter {
  readonly value: number;
  increment(by?: number): void;
  reset(): void;
}

let count = 0;              // module-private: not exported, unreachable from outside
const history: number[] = [];

export function increment(by = 1): void {
  count += by;
  history.push(count);
}

export function reset(): void {
  count = 0;
  history.length = 0;
}

export function getValue(): number {
  return count;
}

// `history` and `count` are genuinely inaccessible. No convention, no underscore.

Module scope is the privacy. An unexported binding cannot be imported, cannot be reached through a property access, and is removed entirely by a bundler if nothing uses it. The interface at the top is the documentation and the check: an implementation that drifts from it is caught the moment something is typed against it.

Three levels of privacy

Mechanism Scope Enforced by Visible at runtime
Not exported from the module the file the module system no — often removed
#field in a class the class the JavaScript runtime no
private in a class the class the compiler only yes, readable and enumerable
A naming convention (_field) nothing nobody yes
class Session {
  #token = "secret";          // truly private
  private userId = "u1";      // compile-time only
  _legacy = "visible";        // a convention, nothing more

  describe() { return this.#token.length + this.userId.length; }
}

const session = new Session();
console.log(Object.keys(session));        // ["userId", "_legacy"]
console.log(JSON.stringify(session));     // {"userId":"u1","_legacy":"visible"}
console.log((session as any).userId);     // "u1"
console.log(session.describe());

Module-level and # are real. private is a promise the compiler keeps and the runtime does not — which matters the moment the object is serialised or logged.

Why not namespace

// The old way. Do not write this in new code.
namespace Geometry {
  const PRIVATE_FACTOR = 2;  // private to the namespace

  export function circumference(radius: number): number {
    return PRIVATE_FACTOR * Math.PI * radius;
  }
}

console.log(Geometry.circumference(1).toFixed(2));

namespace is TypeScript’s pre-modules answer to the same problem, and it is discouraged for reasons that are all practical:

  • It emits an IIFE and an object. Every member access goes through it, so a bundler cannot tree-shake unused members — the whole namespace ships.
  • It reintroduces global state. Namespaces merge across files, so two files can add to one namespace and the result depends on load order.
  • It is not JavaScript. erasableSyntaxOnly and Node’s own type stripping reject it, so code using it cannot run without a real compile step.
  • Modules already do it better. A file is a namespace, import * as Geometry from "./geometry" gives the same call syntax, and the imports say where things come from.
// The replacement, with the same call sites:
// geometry.ts
export function circumference(radius: number): number { return 2 * Math.PI * radius; }

// caller.ts
// import * as Geometry from "./geometry";
// Geometry.circumference(1);
export {};

The one remaining legitimate use is in a declaration file, where declare namespace describes a library that really does attach a nested object to the global scope.

A singleton module

A module is evaluated once, so module state is shared state — which makes the module pattern the simplest singleton there is:

// config.ts
interface Config {
  readonly apiUrl: string;
  readonly timeout: number;
}

let config: Config | undefined;

export function initialise(values: Config): void {
  if (config) throw new Error("config already initialised");
  config = values;
}

export function getConfig(): Config {
  if (!config) throw new Error("config not initialised");
  return config;
}

No class, no static, no getInstance. The caveats are the singleton caveats — hidden global state, order-dependent initialisation, awkward to swap in a test — and they are covered in the singleton lecture. The throw on double initialisation is what turns an order bug into an error instead of a surprise.

Declaring the surface separately

For a module whose consumers should see a contract rather than a list of functions, export the interface and an object that satisfies it:

export interface UserService {
  find(id: string): Promise<{ id: string; name: string } | null>;
  create(name: string): Promise<{ id: string; name: string }>;
}

const cache = new Map<string, { id: string; name: string }>();  // private

export const userService: UserService = {
  async find(id) { return cache.get(id) ?? null; },
  async create(name) {
    const user = { id: crypto.randomUUID(), name };
    cache.set(user.id, user);
    return user;
  },
};

Two properties worth having. A consumer can depend on UserService rather than on this module, so a fake is a one-line object in a test. And adding a method to the object without adding it to the interface makes it invisible — the interface is the surface, not whatever happens to be exported.

Barrel files

The index.ts that re-exports a folder is the module pattern applied to a directory, and it has two real costs:

// features/users/index.ts
export type { User, UserRole } from "./types";
export { userService } from "./service";
export { formatUserName } from "./format";
// Deliberately not exported: ./internal/cache, ./internal/mapper
  • Circular imports. Two modules inside the folder that both import from the barrel form a cycle through it. Inside a folder, import directly from the sibling file.
  • Load cost. Importing one symbol from a barrel evaluates every module it re-exports. With a bundler and sideEffects: false that is mostly tree-shaken; in a test runner or in Node it is not, and a large barrel becomes a measurable startup cost.

Use export type for the type-only re-exports, as above: it guarantees they vanish from the emit and keeps the barrel from dragging in a module just to name a type.

Common mistakes

namespace in new code

Mistake. Wrapping utilities in a namespace for organisation. Why it fails. Nothing is tree-shaken, declarations merge across files, and the syntax is not JavaScript — so stripping-only runtimes reject it. What to do instead. One file per module, and import * as X where the qualified call style is wanted.

private for something that must not leak

Mistake. A private token field on a session class. Why it fails. The property is present, enumerable and in JSON.stringify — a logged object leaks it. What to do instead. #token, or keep it in module scope and never put it on the object.

A barrel imported from inside its own folder

Mistake. import { helper } from "../index" within the same feature folder. Why it fails. A cycle through the barrel, whose symptom is an undefined import at runtime rather than a compile error. What to do instead. Import the sibling file directly; let the barrel serve consumers outside the folder only.

Check yourself

2 questions from the bank on what you just read. Answering here does not affect your quiz history.

What is the typed version of the Module pattern in TypeScript?

A namespace and a module solve the same problem, one of them twenty years later.

Why is namespace discouraged in new TypeScript code?

Practise Design patterns →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.