Global Augmentation
In this page:
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
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
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
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
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
// 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: