Extending global types (e.g. "Window") inside a typescript module

Viewed 31597

If you are writing in typescript, and are not using modules, it is possible to extend the global Window object. For example, this compiles:

interface Window {
    myCounter: number;
}

window.myCounter = window.myCounter || 0;
++window.myCounter;

function outputLoadingDetails() {
    console.log(`myCounter= ${window.myCounter}`)
}

But if I prefix the function outputLoadingDetails with export, it appears I am converting this file into a module. I now get a compiler error when I access window.myCounter.

interface Window {
    myCounter: number;
}

window.myCounter = window.myCounter || 0; // ERROR: property 'MyCounter' does not exist on type `Window`
++window.myCounter;                       // ERROR: property 'MyCounter' does not exist on type `Window`

export function outputLoadingDetails() {
    console.log(`myCounter= ${window.myCounter}`)  // ERROR: property 'MyCounter' does not exist on type `Window`
}

It appears my interface declaration is no longer extending the global Window type.

One workaround I've found is to put the interface declaration into a separate *.d.ts file, and reference this from my module.

But now I'm curious. Is there some way I can extend the Window interface within the module code?

3 Answers

Yes, you just need to wrap the interface into global declaration:

declare global {
    interface Window {
        myCounter: number;
    }
}

Global scope can be augmented from modules using a declare global declarations

More info here


** Make sure the file is treated as a module (has import or export statement, if not - you can add empty export {})

I didn't like modifying the global declaration as modifications would appear in other files.

This was my solution:


interface customWindow extends Window {
  customProperty?: any;
}

declare const window: customWindow;

/* ... */

window.customProperty

interface Window { mycounter:number; }
window=Window;
window.myCounter = window.myCounter || 0;
++window.myCounter; 

I think It may be work but i'm not sure

Related