What is a TypeScript namespace, and how is it declared?
Short answer
A namespace groups related code under a single named container using the 'namespace' keyword, generating a nested object at runtime — it was TypeScript's original way to organize code before ES Modules became the standard, and is mostly used today for organizing types or in…
Advertisement
AModel answer
A namespace groups related code under a single named container using the 'namespace' keyword, generating a nested object at runtime — it was TypeScript's original way to organize code before ES Modules became the standard, and is mostly used today for organizing types or in non-module global scripts.
namespace Validation {
export function isValid(input: string): boolean {
return input.length > 0;
}
}
Validation.isValid('hello'); // trueReal-world example
Organizing a set of related global type definitions in a non-module ambient .d.ts file.
Likely follow-ups
- Why do modern TypeScript style guides generally recommend ES Modules over namespaces?
Related topics