UMD Module Declarations
You'll learn how to write declaration files for libraries that work both as modules and global scripts using export as namespace.
What Is UMD?
UMD (Universal Module Definition) is a pattern that allows JavaScript libraries to work in multiple environments: as a CommonJS module (require), as an AMD module, and as a global variable when loaded via a script tag.
Think of it like a universal power adapter — the same library "plug" works whether you're in a Node.js environment, using a module bundler, or just including it with a <script> tag in the browser.
The export as namespace Syntax
When writing declaration files for UMD libraries, you need to declare both the module exports and the global namespace. TypeScript provides export as namespace specifically for this:
// lodash.d.ts (simplified example)
// First, declare the module with its exports
export function map<T, U>(array: T[], fn: (item: T) => U): U[];
export function filter<T>(array: T[], fn: (item: T) => boolean): T[];
// Then declare it's also available as a global
export as namespace _;
This tells TypeScript: "These exports are available when you import this module, and they're also available globally as _ when loaded via a script tag."
How It Works in Practice
With the declaration above, both of these usage patterns are valid:
// As a module import
import * as _ from 'lodash';
_.map([1, 2, 3], x => x * 2);
// As a global (when loaded via <script> tag)
_.map([1, 2, 3], x => x * 2);
The export as namespace declaration bridges these two worlds, ensuring TypeScript understands both access patterns without confusion or errors.
Key Takeaway: Use export as namespace in declaration files when a library can be both imported as a module and accessed as a global variable, ensuring type safety for UMD libraries in all usage contexts.