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?
To extend the window type in TypeScript, create a . d. ts file where you extend the Window interface adding the names and types of the properties you intend to access on the window object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With