4

I'm using webpack to compile my TypeScript to Javascript and I want to expose a variable to the global scope so others can access it.

I know how to do the following in TypeScript

window["MyVariable"] = 'Hello';

and read it in JavaScript like that

console.log(window.MyVariable);

But I'd prefer if I could just have it in the global scope like that.

console.log(MyVariable);

Is this possible?

Best regards, Nick

Nick
  • 221
  • 2
  • 12

2 Answers2

2

Sure you can do this; TS just adds type safety (and does some transpilation depending on the target ES version).

Since window is the global object in the browser, adding members to it makes them available globally.

Depending on the strictness settings (e.g. disallow implicit any) you might get a compiler error, but that is simple to work around:

(window as any).MyVariable = 'Hello';
Lucero
  • 59,176
  • 9
  • 122
  • 152
2

Whatever exists on the global scope can be accessed without window. in JavaScript. So if you set window['MyVariable'] = 'Hello', you can access it in JavaScript simply with MyVariable.

rid
  • 61,078
  • 31
  • 152
  • 193
  • but not in typescript? – Jonas Wilms Apr 18 '20 at 09:30
  • @JonasWilms, I don't think you can access `MyVariable` from this scenario in TypeScript the same way you can in JavaScript, without typing. But if you declare it, the type checker should not complain. – rid Apr 19 '20 at 08:39