Type-checking for globalThis

TypeScript 3.4 introduces support for type-checking ECMAScript’s new globalThis - a global variable that, well, refers to the global scope.Unlike the above solutions, globalThis provides a standard way for accessing the global scope which can be used across different environments.

  1. // in a global file:
  2. var abc = 100;
  3. // Refers to 'abc' from above.
  4. globalThis.abc = 200;

Note that global variables declared with let and const don’t show up on globalThis.

  1. let answer = 42;
  2. // error! Property 'answer' does not exist on 'typeof globalThis'.
  3. globalThis.answer = 333333;

It’s also important to note that TypeScript doesn’t transform references to globalThis when compiling to older versions of ECMAScript.As such, unless you’re targeting evergreen browsers (which already support globalThis), you may want to use an appropriate polyfill instead.

For more details on the implementation, see the feature’s pull request.