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

Augmenting Third-Party Library Modules

Add missing or custom types to external npm packages without modifying the original library code.

Augmenting Third-Party Library Modules

What you'll learn: How to add missing or custom types to external npm packages without modifying the original library code.

The Problem

You're using a third-party library that either has incomplete types, missing methods, or you've extended it with plugins. TypeScript doesn't know about these additions, causing type errors even though your code works at runtime.

Module Augmentation to the Rescue

Module augmentation lets you "reopen" and extend existing module declarations. You're essentially telling TypeScript: "This library actually has more than what its original types declare."

How It Works

You use the declare module syntax with the exact same module name as the library you're augmenting. TypeScript merges your additions with the original declarations:

// In a .d.ts file or .ts file
declare module 'express' {
  interface Request {
    userId?: string;  // Adding custom property
  }
}

Now TypeScript recognizes request.userId throughout your codebase, even though Express's original types don't include it.

Key Details

  • Place augmentations in .d.ts files or at the top of .ts files
  • The module name must match exactly: 'express', not './express'
  • TypeScript merges interfaces automatically (declaration merging)
  • Your augmentations apply globally once the file is included in compilation
  • Use export {} if needed to force the file into module scope

Common Use Cases

  • Adding custom middleware properties (request.user, request.session)
  • Typing plugin extensions (like adding methods to jQuery or Moment.js)
  • Filling gaps in incomplete third-party types
  • Adding internal-only properties your team uses

Key Takeaway: Module augmentation lets you extend third-party library types safely and globally without forking or patching the original package, keeping your types in sync with runtime behavior.