When working with TypeScript and not using modules, it is possible to extend the global Window
object. For instance, the following code will compile:
interface Window {
myCounter: number;
}
window.myCounter = window.myCounter || 0;
++window.myCounter;
function outputLoadingDetails() {
console.log(`myCounter= ${window.myCounter}`)
}
However, if the function outputLoadingDetails
is prefixed with export
, it seems to convert the file into a module. This results in a compiler error when trying to 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 seems that the interface declaration no longer extends the global Window
type.
An alternate solution is to place the interface declaration in a separate *.d.ts
file and reference it from within the module.
Now the question arises: Is there a way to extend the Window
interface within the module code itself?