TypeScript Namespaces
Namespaces are an older TypeScript feature for grouping related code under a single named object, helping avoid naming collisions before ES modules were widely used.
Today, ES modules (with import/export) are generally preferred over namespaces for organizing code across files. However, you may still encounter namespaces in older codebases or certain declaration files.
namespace Shapes {
export function area(side: number): number {
return side * side;
}
}Declaring a namespace
You group code with the `namespace` keyword, and export the members you want accessible from outside, such as `namespace Shapes { export function area() {} }`.
Namespaces vs modules
Modules (using import/export across files) are the modern standard for code organization. Namespaces are mostly seen in legacy code or type declaration files today.
namespace Shapes {
export function area(side: number): number {
return side * side;
}
}
console.log(Shapes.area(4));16The area function is grouped inside the Shapes namespace and accessed with dot notation.
namespace Utils {
export const PI = 3.14;
export function circleArea(r: number): number {
return PI * r * r;
}
}
console.log(Utils.circleArea(2));12.56Both a constant and a function are grouped and exported from the Utils namespace.
Key points
- Namespaces group related code under one named object.
- Members must be marked `export` to be accessible outside the namespace.
- ES modules are the modern, preferred way to organize code across files.
- Namespaces are mostly found in legacy code and some declaration files.
