Placement and Module Context
What you'll learn: Where to put global augmentations and why they require at least one import or export statement.
The Module Context Rule
When you write global augmentations using declare global, TypeScript has a crucial requirement: the file containing the augmentation must be treated as a module. This means your .d.ts or .ts file needs at least one top-level import or export statement — even if it's completely unrelated to your augmentation.
Why This Matters
TypeScript distinguishes between two kinds of files:
- Script files: Files with no imports or exports. Everything declared in them is automatically global.
- Module files: Files with at least one import or export. These have their own scope.
Global augmentations (declare global) only work in module files. If you try to use declare global in a script file, TypeScript will ignore the block entirely because everything is already global.
The Minimal Fix
The common pattern is to add an empty export at the bottom of your file:
declare global {
interface Window {
myCustomProperty: string;
}
}
// This makes the file a module
export {};
That export {} doesn't export anything, but it transforms the file from a script into a module, allowing the declare global block to work correctly.
Placement Strategy
Put your global augmentation files wherever they'll be included in your TypeScript compilation. Common locations:
- A
types/ortypings/directory at your project root - Alongside the code that uses the augmented globals
- In your
src/directory with your other TypeScript files
Just ensure the file is picked up by your tsconfig.json (via include or default discovery).
Key Takeaway: Global augmentations must live in module files (with at least one import or export), and should be placed where your TypeScript compiler will find them — typically in a dedicated types directory or alongside related source code.