What is namespace in Typescript ? (original) (raw)

Last Updated : 17 Mar, 2025

In TypeScript, a namespace is a way to organize code logically and prevent naming conflicts between identifiers. It allows developers to group related functionalities, such as interfaces, classes, functions, and variables, within a dedicated scope.

Namespaces are particularly useful for structuring large applications, avoiding global scope pollution, and maintaining a clear hierarchy.

Declaring and Using a Namespace in TypeScript

Here’s a simple example demonstrating how to create and use a namespace in TypeScript:

JavaScript `

namespace Geometry { export class Circle { constructor(public radius: number) {}

area(): number {
  return Math.PI * this.radius ** 2;
}

} } const circle = new Geometry.Circle(5); console.log(circle.area());

`

**Output:

78.53981633974483

**More Examples of Namespace in TypeScript

**Declaring and Accessing a Simple Namespace

JavaScript `

namespace MyNamespace { export function myFunction() { console.log('This is my function in MyNamespace'); } }

MyNamespace.myFunction();

`

**Output:

This is my function in MyNamespac

**Declaring and Accessing a Nested Namespace

JavaScript `

namespace MyNamespace { export namespace MySubNamespace { export function myFunction() { console.log('This is my function in MySubNamespace'); } } }

MyNamespace.MySubNamespace.myFunction();

`

**Output:

"This is my function in MySubNamespace"

**Benefits of Using Namespaces

Namespaces vs. Modules in TypeScript

Here are the main differences between Namespaces and Modules in TypeScript:

Feature Namespaces Modules
**Usage TypeScript-specific Standard JavaScript feature
**Scope Works within a global file Works across multiple files
**Syntax Uses namespace keyword Uses import/export
**Modularity Less flexible More scalable and reusable
**Recommendation Not preferred for new projects Recommended for modern development