Language: EN

typescript-namespaces

Namespaces in TypeScript

Namespaces are a way to organize and group our code into logical modules to avoid name collisions between different parts of our program.

A namespace in Typescript encapsulates variables, functions, classes, and other elements in a container. This allows us to group and organize our code, avoiding conflicts and improving readability and maintainability.

To define a namespace in Typescript, we use the namespace keyword followed by the name we want to assign to the namespace. For example:

namespace MyNamespace {
  export function greet() {
    console.log("Hello from MyNamespace!");
  }
}

In this example,

  • We create a namespace called MyNamespace
  • It contains a function greet.
  • The export declaration allows the function to be accessible outside the namespace.

Using namespaces

Once we have defined a namespace, we can use it in other parts of our program. To access the elements within a namespace, we use the NamespaceName.ElementName syntax. For example:

MyNamespace.greet();

In this case, we are calling the greet function that is located within the MyNamespace namespace.

Nesting namespaces

In Typescript, it is also possible to nest namespaces within other namespaces. This allows us to further organize our code and avoid name collisions. For example:

namespace MyNamespace {
  export namespace SubNamespace {
    export function sayGoodbye() {
      console.log("Goodbye from SubNamespace!");
    }
  }
}

In this case,

  • We have nested a namespace called SubNamespace within the MyNamespace
  • The function sayGoodbye is located within the SubNamespace
  • To access this function, we use the MyNamespace.SubNamespace.sayGoodbye() syntax