TypeScript Course
TypeScript
/
Intermediate

Namespaces

Definition

A TypeScript-specific way to organize code before ES Modules became the standard. They group logically related code under a single global object.

Explain Like I'm New

Before modern JavaScript `import/export` existed, if you had two functions named `calculate()`, they would clash. Namespaces were TS's solution to group them: `MathUtils.calculate()` and `PhysicsUtils.calculate()`. Today, they are largely obsolete.

Real World Example

You will mostly see Namespaces in legacy codebases, or when writing Declaration Files (`.d.ts`) to describe old JavaScript libraries (like jQuery) that attach themselves globally to the `window` object.

Common Use Cases

  • •Legacy code support
  • •Typing global `<script>` tag libraries

Interactive Example

// DEFINITION
namespace Validation {
  // Must export the interface to be visible outside the namespace
  export interface StringValidator {
    isAcceptable(s: string): boolean;
  }

  const lettersRegexp = /^[A-Za-z]+$/;

  // Must export the class too
  export class LettersOnlyValidator implements StringValidator {
    isAcceptable(s: string) {
      return lettersRegexp.test(s);
    }
  }
}

// USAGE (Accessed via dot notation)
const myValidator = new Validation.LettersOnlyValidator();
myValidator.isAcceptable("Hello"); // true

Interview Questions

basic

  • Should you use Namespaces for new TypeScript projects?

intermediate

  • How do you access a function inside a Namespace?

advanced

  • What is the difference between a Namespace and a Module?

Flash Cards

Question

Should you use them for new projects?

Click to reveal answer
Answer

No! The official TypeScript documentation recommends using standard ES Modules (`import/export`) for all new modern code. Namespaces should only be used for typing global legacy libraries.

Question

Namespace vs Module?

Click to reveal answer
Answer

A Module is a file that contains `import/export`. It has its own file scope. A Namespace is an object created in the global scope (or inside a module) to group properties. Modules are native to JS; Namespaces are a TS-only invention.