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.
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 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).
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 .
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;
}
}
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