Course contentsShow
← TypeScript
Lesson 1168 of 1,79627. Declaration FilesFree lesson

Augmenting Namespaced Modules

Extend modules that use namespace-style exports by augmenting the namespace within a module block.

Augmenting Namespaced Modules

You'll learn how to extend modules that use namespace-style exports by augmenting the namespace within a module block.

The Core Idea

Some older libraries or TypeScript codebases organize their exports using namespaces instead of modern ES modules. When you need to add types to these libraries—perhaps adding a missing method or property—you can't just augment the module directly. You need to augment the namespace that lives inside that module.

Think of it like adding a room to a house that has a specific architectural style. The house (the module) contains named wings (namespaces), and you need to extend the right wing in the right way.

The Pattern

When a library exports a namespace, you use nested augmentation: declare the module first, then declare the namespace inside it:

// Imagine a library 'legacy-charts' with this structure:
// export namespace ChartUtils { ... }

declare module 'legacy-charts' {
  namespace ChartUtils {
    // Add new properties or methods to the namespace
    function formatAxis(value: number): string;
    interface Options {
      customTheme?: string;
    }
  }
}

The outer declare module targets the module name. The inner namespace block matches the namespace exported by that module. This dual-layer approach tells TypeScript: "In this module, within this namespace, add these new types."

Why This Matters

Libraries that predate ES modules often use namespaces for organization. Without this technique, you can't safely add types to their APIs. With it, you maintain type safety while working with legacy code, ensuring autocomplete and type checking work correctly even when extending old-style exports.

Key Takeaway: Augment namespaced modules by nesting a namespace declaration inside a declare module block—matching the structure the library uses to organize its exports.