TypeScript Namespaces & Modules Cheat Sheet
Compares ES module import/export syntax with legacy TypeScript namespaces, covering declaration merging and when each approach fits.
2 PagesIntermediateApr 15, 2026
ES Modules (the Modern Default)
Standard import/export syntax for organizing TypeScript code today.
typescript
// math.tsexport function add(a: number, b: number): number { return a + b; }export const PI = 3.14159;export default class Calculator { /* ... */ } // default export// app.tsimport Calculator, { add, PI } from './math';import * as MathUtils from './math'; // namespace import// Re-exportingexport { add as sum } from './math';export * from './math';
Namespaces (Legacy, Single-File Grouping)
Group related code under one name without ES module tooling.
typescript
namespace Geometry { export interface Point { x: number; y: number; } export function distance(a: Point, b: Point): number { return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2); } // Nested namespaces export namespace Shapes { export class Circle { constructor(public radius: number) {} } }}const p1: Geometry.Point = { x: 0, y: 0 };const c = new Geometry.Shapes.Circle(5);
Declaration Merging with Namespaces
Attach static members to a class using a same-named namespace.
typescript
// Attach static members/types to a class or function via a same-named namespaceclass Album { constructor(public title: string) {}}namespace Album { export function create(title: string): Album { return new Album(title); }}const a = Album.create('Abbey Road');
Module Concepts
Key vocabulary for how TypeScript exposes and resolves code.
- export- Marks a declaration as visible outside its module
- export default- One per module; imported without curly braces
- import type- Imports only type information, guaranteed to be erased at compile time
- module vs namespace keyword- 'module X {}' is a deprecated alias for 'namespace X {}'
- triple-slash reference- /// <reference path="./file.ts" /> links namespace files together (pre-module era)
- ambient declarations- declare namespace X {} describes shapes for existing global/JS code without emitting runtime code
- moduleResolution setting- tsconfig option controlling how import paths are resolved (node16, bundler, etc.)
Pro Tip
Avoid namespaces in new code that targets modern bundlers - they predate ES modules and mainly still show up for organizing global .d.ts ambient type declarations or in legacy codebases; use ES module import/export for everything else.
Was this cheat sheet helpful?
Explore Topics
#TypeScriptNamespacesModules#TypeScriptNamespacesModulesCheatSheet#Programming#Intermediate#ESModulesTheModernDefault#Namespaces#Legacy#Single#Git#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance