What does "declare global{ interface Window{ analytics: any; } }" mean in angular/Typescript?

Viewed 1742

I have this piece of code (from here), that I am trying to understand what it does:

declare global {
  interface Window { analytics: any; }
}

I have seen here what declare global means.

And I have seen from this question what interface means.

I know what the window object means.

What I do not understand is what the code above means. Correct if I am wrong. The code means that the analytics variable has is now recognized as a global object of type any. Also that it has the window properties that you can access, as shown by interface Window.

Also why do we declare global{ /**variable being declared gloabal here.*/ }. Why are we using this semantic to declare a global variable. Why does the variable go inside the curly braces as opposed to something like var goat?

2 Answers

This is called Global augmentation, it's a special syntax/keyword which allows to declare global variables. These declarations get merged with the ECMAScript definition files thanks to the declaration merging ability of TypeScript.

If answer your exact question, Segment.io code snippet you linked above

declare global {
  interface Window { analytics: any; }
}

should be put in you Angular src/app/app.module.ts after the imports but before the @NgModule decorator to avoid compile errors.

Related