TypeScript NameSpace

Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.


A namespace is used to group related variables, functions, interfaces, or classes together under a single name.

Here's a simple example of a namespace. You can read the rest of the tutorial to learn more.

Example

namespace MathUtils {
  export function add(a: number, b: number): number {
    return a + b;
  }
}

console.log(MathUtils.add(5, 10)); 
// Output: 
// 15

Here,

  • MathUtils is a namespace.
  • add() is a function inside it..
  • The export keyword makes the function accessible outside the namespace.

Syntax of NameSpace

The syntax of namespace is:

namespace NamespaceName {
  export function functionName() {
    // function body
  }

  export class ClassName {
    // class body
  }
}

Here,

  • namespace is the keyword to define a namespace.
  • export makes functions or classes available outside the namespace.

Example 1: NameSpace with Multiple Functions

namespace StringUtils {
  export function toUpper(text: string): string {
    return text.toUpperCase();
  }

  export function toLower(text: string): string {
    return text.toLowerCase();
  }
}

console.log(StringUtils.toUpper("hello")); // HELLO
console.log(StringUtils.toLower("WORLD")); // world

Example 2: NameSpace with a Class

namespace App {
  export class User {
    constructor(public name: string) {}
    greet() {
      console.log("Hello, " + this.name);
    }
  }
}

const user = new App.User("Alice");
user.greet(); // Hello, Alice

Example 3: Nested NameSpace

namespace Company {
  export namespace HR {
    export class Employee {
      constructor(public name: string) {}
    }
  }
}

const emp = new Company.HR.Employee("John");
console.log(emp.name); // John

When to Use a NameSpace

Namespaces are useful when:

  • You want to group related code (functions, classes, etc.) together.
  • You want to avoid naming collisions in global scope.
  • You're working on older projects or in environments that don't use ES6 modules.

Key Differences Between NameSpace and Modules

While namespaces and modules can both be used to organize code, here are some differences:

NameSpace Module
NameSpace is a TypeScript feature. Modules are features of both JavaScript and TypeScript.
They are used for organizing code in one file. They allow code to be split across multiple files.
They use export within a single file. They use import and export.

Read More:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges