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

Global Augmentation in .d.ts Files

Using ambient declaration files to augment globals without mixing runtime and type code.

Global Augmentation in .d.ts Files

What you'll learn: How to use ambient declaration files (.d.ts) to augment global types without mixing runtime code and type definitions.

The Core Idea

So far, you've seen how to augment globals using declare global syntax. But there's an important architectural consideration: where should this augmentation code live?

The best practice is to place global augmentations in dedicated .d.ts files (ambient declaration files) rather than mixing them with your runtime TypeScript code. This separation keeps your type-only declarations distinct from executable code, making your codebase cleaner and more maintainable.

Why Separate Declaration Files?

Think of .d.ts files as "type-only blueprints." They don't generate any JavaScript output—they exist purely to inform the TypeScript compiler about type shapes. When you augment globals in a .d.ts file:

  • You clearly signal "this is type information only"
  • Build tools can optimize better (no runtime overhead concerns)
  • Your project structure becomes more organized
  • Other developers immediately recognize type-only modifications

How It Works

Create a file like global-augmentations.d.ts in your project:

// global-augmentations.d.ts

declare global {
  interface Window {
    analytics: {
      track(event: string): void;
    };
  }
}

export {};

Notice the export {} at the bottom—this forces the file to be treated as a module context, which is required for declare global to work properly.

Now, anywhere in your project, you can reference window.analytics with full type safety, and the TypeScript compiler knows about it, but no JavaScript code is generated from this file.

Key Takeaway: Use dedicated .d.ts files for global augmentations to keep type declarations separate from runtime code, improving code organization and making type-only modifications explicit.