Script Valley
TypeScript: Complete Course from Zero
Advanced Types and Real-World PatternsLesson 6.4

TypeScript module augmentation and declaration merging

declaration merging for modules, augmenting third-party types, ambient modules, global augmentation, .d.ts files basics

Module augmentation

Add properties to an existing module's types without forking it:

// Augment Express Request type
import "express";

declare module "express" {
  interface Request {
    currentUser?: { id: string; role: string };
  }
}

// Now usable in route handlers:
app.get("/profile", (req, res) => {
  const user = req.currentUser; // typed!
});

Global augmentation

declare global {
  interface Window {
    analytics: AnalyticsClient;
  }
}

window.analytics.track("pageview"); // typed

Ambient module declarations

For packages with no type definitions, create a .d.ts file:

// types/legacy-lib.d.ts
declare module "legacy-lib" {
  export function parse(input: string): Record;
  export const version: string;
}

Module augmentation is the correct way to extend third-party types. Never modify node_modules directly — changes are lost on reinstall.

Up next

TypeScript project configuration strict mode and performance tips

Sign in to track progress