🔷 TypeScript Intermediate

What is a namespace in TypeScript?

Answer

A namespace is a TypeScript-specific way to organize code under a named scope, preventing naming collisions in the global space. Syntax: namespace Validation { export interface StringValidator { isAcceptable(s: string): boolean; } export class LettersOnlyValidator implements StringValidator { ... } }. Access: const validator = new Validation.LettersOnlyValidator();. Namespaces can be nested and split across multiple files. Before ES6 modules, namespaces (formerly "internal modules") were the primary way to organize TypeScript code. Namespaces vs Modules: today, ES module syntax (import/export) is strongly preferred for organizing code — namespaces are considered legacy for new code. However, namespaces are still useful for: (1) ambient type declarations in .d.ts files, (2) global augmentation, (3) organizing types without creating separate files. Declaration merging also works with namespaces, allowing you to merge namespaces with existing classes or functions.