Namespaces in Declarations
What you'll learn: How to organize related type declarations under a single namespace to prevent global scope pollution and improve declaration file structure.
Why Namespaces in Declarations Matter
When writing declaration files for libraries or global scripts, you often need to group related types, functions, and variables together. Without organization, everything ends up in the global scope, creating a confusing mess of names. Namespaces (or declare namespace) solve this by creating a named container for your declarations.
Think of namespaces like folders on your computer. Instead of dumping all your files on the desktop, you organize them into folders. Similarly, instead of declaring dozens of unrelated types at the top level, you group them under meaningful names.
Basic Namespace Declaration Syntax
In a .d.ts file, you use namespace or declare namespace to create a grouping:
// myLibrary.d.ts
declare namespace MyLibrary {
function initialize(config: Config): void;
interface Config {
apiKey: string;
timeout: number;
}
class Manager {
start(): void;
stop(): void;
}
}
Now users access these declarations through the namespace:
MyLibrary.initialize({ apiKey: "123", timeout: 5000 });
const mgr = new MyLibrary.Manager();
When to Use Namespaces in Declarations
Use namespaces in declaration files when:
- Declaring global libraries that attach to
windoworglobal - Grouping related utilities that don't use ES modules
- Avoiding name collisions between different parts of a large API
- Typing legacy scripts that use namespaced patterns
Namespaces are particularly common when typing jQuery plugins, global libraries, or browser APIs.
Nested Namespaces
You can nest namespaces for deeper organization:
declare namespace App {
namespace Utils {
function formatDate(date: Date): string;
}
namespace API {
function fetch(url: string): Promise<Response>;
}
}
// Usage: App.Utils.formatDate(...)
Key Takeaway: Use namespace or declare namespace in declaration files to organize related types, functions, and classes under a single name, keeping the global scope clean and your API intuitive.