TypeScript Modules and Namespaces
Organizing code is crucial for maintainability. TypeScript provides two main ways to organize code: Modules (based on the ES6 standard) and Namespaces (a TypeScript-specific way to group code).
1. Modules (Recommended)
Modules are the standard way to organize code in modern JavaScript and TypeScript. A file is considered a module if it contains at least one top-level import or export. Variables, functions, classes, etc., are private to the module unless explicitly exported.
Exporting
// mathUtils.ts
export function add(x: number, y: number): number {
return x + y;
}
export const PI = 3.14;
// Default export
export default class Calculator {
// ...
}
Importing
// app.ts
import Calculator, { add, PI } from "./mathUtils";
console.log(add(10, 5));
const calc = new Calculator();
Renaming Imports
import { add as sum } from "./mathUtils";
2. Namespaces (Legacy/Specific Use Cases)
Namespaces (formerly "Internal Modules") are a TypeScript-specific way to organize code using the namespace keyword. They compile into JavaScript objects (IIFEs) to prevent global scope pollution.
They are useful for grouping utilities logically without using a module loader, or for structuring type definitions (.d.ts) for third-party libraries.
Syntax
// Validation.ts
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
const lettersRegexp = /^[A-Za-z]+$/;
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return lettersRegexp.test(s);
}
}
}
// Usage
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["Letters only"] = new Validation.LettersOnlyValidator();
Multi-file Namespaces
You can split namespaces across files using reference tags (though this is rarely used in modern projects).
/// <reference path="Validation.ts" />
3. Modules vs. Namespaces
| Feature | Modules | Namespaces |
|---|---|---|
| Standard | ECMAScript Standard (ES6) | TypeScript Specific |
| Loading | Handled by Node.js or Bundlers (Webpack) | Just global objects (script tags) |
| Recommendation | Use for almost everything | Use for legacy apps or .d.ts files |