javascripttypescriptwindow-object

Accessing Window Object from .tsx file


Typically in my .ts files I can access the window object by calling something such as:

(<any>window).myObject

I am getting compilation errors for this in my .tsx files. Is there any way I can access it from a .tsx file?

Thanks.


Solution

  • You can use the as syntax for type assertion. This is the alternate syntax for type assertion as <type>obj conflicts with JSX syntax:

    (window as any).myObject
    

    The above will work, however if you want strong typing consider augmenting the Window interface to add your property so you will get compile-time type checking:

    declare global {
        interface Window {
            myObject: YourObjectType;
        }
    }