reza
reza

Reputation: 6358

How to use a global variable in HTML and use it in typescript?

I need to define a variable in my index.html file and use it in my angular4/typescript code and I get a compile error.

my compile error is:

Error:(109, 27) TS2339: Property 'standalone' does not exist on type 'Window'.

the variable definition in HTML is: var standalone = 'true';

    System.import('app').catch(function (err) {
        console.error(err);
    });
</script>

the typescript code is:

if(window.standalone !== undefined) {
    console.log('standalone');
}

Anyone sees what I am doing wrong?

Upvotes: 3

Views: 1485

Answers (1)

Estus Flask
Estus Flask

Reputation: 222493

Global variables should be declared as globals in TypeScript:

declare var standalone: boolean;

In order to be referenced window property, a global should be also specified as such:

declare global {
  interface Window {
    standalone: boolean;
  }
}

If global variable is used one or several times and cannot benefit from type checks, types can be intentionally skipped instead:

if((<any>window).standalone !== undefined) ...

Or:

if(window['standalone'] !== undefined) ...

Upvotes: 3

Related Questions