Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 429
Andrew Shepherd Avatar asked Nov 06 '17 05:11

Andrew Shepherd


People also ask

How do I extend a TypeScript window?

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.


2 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 {})

like image 142
Aleksey L. Avatar answered Sep 25 '22 22:09

Aleksey L.


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

like image 34
Bayan Bennett Avatar answered Sep 24 '22 22:09

Bayan Bennett