Skip to content

Module Augmentation

In one line

Module augmentation uses declare module to add types/methods to existing modules like library types.

In simple words

Module augmentation lets you extend existing modules' type declarations without modifying the original source. Use declare module "module-name" to add new exports or modify existing types.

Common use cases:

  1. Extending library types — add methods to a third-party class
  2. Plugin patterns — declare types for plugins that add functionality
  3. Declaration merging — combine interface declarations

TypeScript merges augmented declarations with the original. This is type-only — no runtime effect. It's powerful for extending Express requests, Jest matchers, Redux state, etc.

Example

typescript
// Augment Express Request to include a custom property
declare module "express-serve-static-core" {
  interface Request {
    user?: { id: string; name: string };
  }
}

// Now req.user is typed everywhere
import express from "express";
const app = express();
app.use((req, res, next) => {
  req.user = { id: "1", name: "Alice" }; // Typed!
  next();
});

// Augment Array prototype (for demonstration)
declare global {
  interface Array<T> {
    last(): T | undefined;
  }
}

declare module merges new types into existing modules. Express's Request now has a typed user property without modifying the library.

Common confusions

  • Confused with: ambient module

    The difference: An ambient module (declare module 'foo') describes a module that exists at runtime but has no TypeScript types. Module augmentation (declare module 'foo' { ... }) adds to an already-typed module. Ambient creates from scratch; augmentation extends existing.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary