2

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?

YulePale
  • 6,688
  • 16
  • 46
  • 95
  • You're asking about absolute basics of TypeScript. Please first read the tutorial https://www.typescriptlang.org/docs/, at least until you understand `interface Window { analytics: any; }`. Then https://www.typescriptlang.org/docs/handbook/declaration-merging.html should answer your whole question. – jabaa Nov 24 '21 at 11:14
  • 1
    Sometimes I find the docs to be a bit cryptic. We all learn differently. Sometimes we need people to point us to what may seem obvious to them. The end goal is that we learn. From your comment and the answer I now have a better understanding than before. Thank you. – YulePale Nov 24 '21 at 14:15
  • Stack Overflow is not the best place to ask about basic language features: [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) You should at least read the beginner tutorial. – jabaa Nov 24 '21 at 14:22

2 Answers2

7

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.

Guerric P
  • 30,447
  • 6
  • 48
  • 86
1

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.

Nisal Gunawardana
  • 1,345
  • 16
  • 20