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.
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.
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;
}
}
The syntax <type>
is being deprecated by the ts team. This is because there is too much ambiguity between it and the new jsx
syntax. Instead the ts team introduced the as
operator for type assertions.
So this syntax:
(window as any).things
is more update to date.
This change was done, because basically, its very tough to tell a compiler when is such a syntax relating to a type or a jsx-element. Likewise the notation becomes much harder to read (see below for example):
<Component>
{<String>something}
</Component>
Some more detail can be found here https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html#as-foo-vs-foo and here https://github.com/Microsoft/TypeScript/issues/296
Further Explanation on @Saravana Answer,
best way is to have this defined in your types
folder, and add a definition file with .d.ts
extention, i.e: window.d.ts
and place your extended definitions for the window object, as typescript global augmentation typically offers merging interfaces.
declare global {
interface Window {
myObject: YourObjectType;
}
}
// but make sure to export that as default so Typescript will consider it automatically on the project
export default global;