Namespaces in Declaration Files
You'll learn how to use namespace syntax in .d.ts files to organize types for legacy or global-scope code.
What Are Namespaces in Declaration Files?
When you're writing declaration files for older JavaScript libraries or code that exposes global APIs, you often need to organize related types together. Namespaces provide a way to group these type definitions under a single top-level name, preventing pollution of the global scope while maintaining compatibility with how the library actually works.
Think of namespaces like filing cabinets for your types. Instead of throwing all your type definitions loosely into the global scope (like papers scattered on a desk), you organize them into labeled drawers. This is especially useful when describing libraries that were written before ES modules became standard.
When to Use Namespaces in Declaration Files
Namespaces shine in declaration files when:
- You're typing a library that exposes a global variable (like
$for jQuery) - The library organizes its API with nested properties on a single object
- You're working with UMD modules that can be used both globally and as imports
- You need to merge types across multiple declaration files
The declare namespace syntax tells TypeScript "this shape exists globally" without actually creating runtime code.
The Basic Pattern
// In globals.d.ts
declare namespace MyLibrary {
function doSomething(value: string): void;
const version: string;
interface Options {
timeout: number;
retries: number;
}
}
This describes a global object called MyLibrary with methods, properties, and types. Users can now reference MyLibrary.doSomething() and MyLibrary.Options with full type safety, even though the actual JavaScript runs globally.
Key Takeaway: Namespaces in declaration files organize types for global-scope or legacy code patterns, allowing you to group related type definitions under a single name while maintaining compatibility with non-modular JavaScript libraries.