← Back to TypeScript Course | Chapter 11: Type Declarations and DefinitelyTyped | Lesson 5 of 5

Global Augmentation

Global augmentation lets a module add declarations to global types such as Window or built-in prototypes. It is useful when external scripts or application code add global APIs.

Understanding Global Augmentation

Global augmentation lets you add new members to types that are available everywhere in your program without an import — most commonly the built-in Window or globalThis objects — using a declare global block.

Example: Understanding Global Augmentation

typescript
declare global {
  interface Window {
    myGlobalFlag: boolean;
  }
}
console.log("declare global adds members available everywhere, no import needed");
export {};

Extending Window

Extending Window is the standard way to type a global variable that some other script attaches to the browser's window object, like an analytics SDK loaded via a <script> tag before your bundle runs.

Example: Extending Window

typescript
declare global {
  interface Window {
    analytics: { track(event: string): void };
  }
}
console.log("Window.analytics typed for a script-tag-loaded SDK");
export {};

Extending Global Interfaces

You can also augment other ambient global interfaces beyond Window, such as globalThis itself in a Node environment, to describe process-wide globals your code relies on but doesn't import.

Example: Extending Global Interfaces

typescript
declare global {
  interface globalThis {
    appConfig: { env: string };
  }
}
console.log("globalThis extended for a Node-style global");
export {};

Adding Global Methods

Adding a global method (like a polyfill you know is present, e.g. structuredClone) to the global interface lets you call it without TypeScript complaining that the method doesn't exist on that built-in type.

Example: Adding Global Methods

typescript
declare global {
  interface Window {
    structuredClone<T>(value: T): T;
  }
}
console.log("Polyfilled global method typed via declare global");
export {};

Best Practices

Because global augmentations affect the entire program's type space at once, keep them narrow and well-documented, and prefer scoped module augmentation wherever it's actually possible instead of reaching for the global scope.

Example: Best Practices

typescript
// Keep global augmentations narrow and documented;
// prefer module augmentation when the scope isn't truly global.
declare global {
  interface Window {
    __APP_VERSION__: string;
  }
}
console.log("Narrow, well-documented global augmentation");
export {};
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.