3

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?

4
  • I do something similar in one of my projects and I found you can’t simply access the window object like that. Check this out for a simple(ish) alternative: juristr.com/blog/2016/09/ng2-get-window-ref/… Commented Jan 3, 2018 at 23:53
  • I am surprised that this is this involved. One would think this is not an uncommon thing to want to do. But thanks Commented Jan 4, 2018 at 0:02
  • if((window as any).standalone !== undefined) { console.log('standalone'); } Commented Jan 4, 2018 at 1:06
  • thank you that last comment is correct and it works. How do I give you credit for your response? Commented Jan 4, 2018 at 15:58

1 Answer 1

3

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) ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.