Namespaces in TypeScript
Namespaces in TypeScript — the core idea
Namespaces group related TypeScript declarations and can be useful in some non-module or declaration contexts. Modern application code generally favors ES modules for cross-file organization. Namespaces are a language feature, not a replacement for Node.js module loading.
What you’ll learn
- Explain namespaces in typescript with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: The namespace compiles to a JavaScript object-like container for the exported function. Calling Geometry.area computes 4 * 6. An unexported namespace member would not be accessible outside it.
Keep the boundary clear: Do not confuse namespace exports with ES module exports; their cross-file loading and scoping rules differ.
See the idea as a flow
Run the complete TypeScript example
Save the code as namespaces.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
namespace Geometry {
export function area(width: number, height: number): number { return width * height; }
}
console.log(Geometry.area(4, 6));Verified output
24Build: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable namespaces.ts; run: node namespaces.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
The namespace compiles to a JavaScript object-like container for the exported function. Calling Geometry.area computes 4 * 6. An unexported namespace member would not be accessible outside it.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
Do not confuse namespace exports with ES module exports; their cross-file loading and scoping rules differ.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Add Geometry.perimeter() and compare calling it with importing a function from an ES module.
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
Namespaces group related TypeScript declarations and can be useful in some non-module or declaration contexts.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.