Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 342
Daniel R Avatar asked Dec 28 '17 13:12

Daniel R


People also ask

Can I access window object in React?

Any property attached to the window object can be accessed from any script on the web page, including the script for the React app. Since window is a global object, the React code can also access its properties, as shown below.

How do I view a TSX file?

How to open a TSX file. Because TSX files are plain text files, you can open them in any text editor. However, TSX files are meant to be opened and edited in source code editors, such as Microsoft Visual Studio (Windows) or Github Atom (cross-platform).

How do I get a Windows in TypeScript?

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. TypeScript looks for .


1 Answers

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;
    }
}
like image 91
Saravana Avatar answered Sep 18 '22 13:09

Saravana