Namespace Basics
In this page:
Creating a Namespace
Use the namespace keyword to create a named container for related declarations, grouping them under a single accessible name without needing separate files or an ES module system.
Example: Creating a Namespace
namespace Shapes {
export function area(side: number) {
return side * side;
}
}
console.log(Shapes.area(4));
Exporting Namespace Members
Members inside a namespace must be exported from it if code outside the namespace needs to access them, mirroring how modules control what's visible outside their own boundary.
Example: Exporting Namespace Members
namespace MathUtils {
export const PI = 3.14159;
function internalHelper() { return "hidden"; }
}
console.log(MathUtils.PI);
Nested Namespaces
Namespaces can contain other namespaces, nesting related declarations into deeper, more specific groupings, similar to how packages can be nested inside other packages. Deeply nested namespaces are accessed with dotted paths, like Outer.Inner.member.
Example: Nested Namespaces
namespace Outer {
export namespace Inner {
export const value = 42;
}
}
console.log(Outer.Inner.value);
Namespaces with Classes
Classes can be exported from namespaces and then accessed through the namespace name, letting a namespace bundle related classes, interfaces, and functions together under one umbrella.
Example: Namespaces with Classes
namespace Shapes {
export class Circle {
constructor(public radius: number) {}
}
}
const c = new Shapes.Circle(5);
console.log(c.radius);
Namespaces and Modern Modules
Namespaces are an older TypeScript organization mechanism that predates widespread ES module support; for modern applications, ES modules are the recommended way to organize code instead.
Example: Namespaces and Modern Modules
// Older style:
namespace Legacy {
export const value = 1;
}
// Modern style (recommended):
// export const value = 1;
console.log(Legacy.value);
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: