Augmenting Built-in Global Interfaces
What you'll learn: How to safely extend TypeScript's built-in global interfaces like Window, NodeJS.Global, or globalThis to add your own custom properties.
Why Augment Global Interfaces?
Sometimes you need to add properties to global objects that exist at runtime but TypeScript doesn't know about. For example, you might attach analytics tracking to the browser's window object, add custom properties to Node.js's global, or extend globalThis for cross-environment code.
Without augmentation, TypeScript will complain that these properties don't exist, even though they work perfectly fine at runtime.
The Basic Pattern
You use declare global combined with interface merging to add properties to built-in globals:
declare global {
interface Window {
myCustomProperty: string;
}
}
// Now TypeScript knows about it
window.myCustomProperty = "Hello!";
console.log(window.myCustomProperty); // ✓ Type-safe
Extending Different Global Interfaces
Browser environment (Window):
declare global {
interface Window {
analytics: {
track: (event: string) => void;
};
}
}
window.analytics.track("page_view"); // ✓ Works
Node.js environment (NodeJS.Global):
declare global {
namespace NodeJS {
interface Global {
appVersion: string;
}
}
}
global.appVersion = "1.0.0"; // ✓ Type-safe in Node
Cross-environment (globalThis):
declare global {
var API_KEY: string; // Using 'var' for global scope
}
globalThis.API_KEY = "secret"; // Works everywhere
Real-World Example
Imagine you're adding environment configuration that's injected at build time:
declare global {
interface Window {
ENV: {
API_URL: string;
DEBUG_MODE: boolean;
};
}
}
// Later in your code:
const apiUrl = window.ENV.API_URL; // string
const debug = window.ENV.DEBUG_MODE; // boolean
Important Guidelines
Remember to add export {} at the bottom of augmentation files if they don't already have imports/exports—this forces TypeScript to treat the file as a module, which is required for global augmentation to work properly.
Key Takeaway: Use declare global with interface merging to type-safely extend built-in global interfaces like Window, NodeJS.Global, or globalThis when you add custom properties at runtime that TypeScript needs to know about.