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?