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

Avoiding Global Pollution

When to use module augmentation instead and keeping the global namespace minimal and intentional.

Avoiding Global Pollution

You'll learn when to use module augmentation instead of global declarations and why keeping the global namespace minimal matters.

What Is Global Pollution?

When you use declare global to add things to the global scope, you're modifying a shared space that every file in your entire project can access. This is called "polluting" the global namespace because you're adding to something that should remain clean and minimal.

Think of the global namespace like a town square. If everyone starts leaving their belongings there, it becomes cluttered, confusing, and things start conflicting. The same happens with global declarations—too many can cause naming collisions and make it unclear where types come from.

When to Use Module Augmentation Instead

Module augmentation targets a specific module, keeping changes contained:

// ✅ Good: Augmenting a specific module
declare module 'express' {
  interface Request {
    user?: User;
  }
}

Global augmentation affects everything everywhere:

// ⚠️ Careful: Polluting the global scope
declare global {
  interface Request {
    user?: User;
  }
}

Use module augmentation when you're extending a library's types. Use global augmentation only when you truly need something available everywhere (like extending built-in types or adding actual global variables).

Keep It Minimal and Intentional

Every global declaration should answer: "Does every file in my project need this?"

If only your Express routes need custom Request properties, augment the Express module. If you're adding a utility function used in just a few files, export it from a module instead of making it global.

Good practice: Document why you added global types with comments explaining the necessity.

Key Takeaway: Prefer module augmentation to keep type changes scoped; only use global augmentation when you genuinely need project-wide availability, and always keep the global namespace as clean as possible.