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.
// in a global file:
var abc = 100;
// Refers to 'abc' from above.
globalThis.abc = 200;
Note that global variables declared with let
and const
don’t show up on globalThis
.
let answer = 42;
// error! Property 'answer' does not exist on 'typeof globalThis'.
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.