6

i am trying to access the globalThis property, but get the error:

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature`.
// both getting...
if (!globalThis.foo) {}

// and setting...
globalThis.foo = 'bar

the only thing i can find online about this, refers to using window, and provides declarations to support it, but not for globalThis. anyone know how to support this?

brewster
  • 4,342
  • 6
  • 45
  • 67

1 Answers1

13

According to the globalThis documentation, it looks like the "right" way to do this is to declare a global var named foo. That will add to globalThis.

If your code is in global scope, then this will work:

var foo: string;

If your code is in a module, you need to wrap that in a global declaration:

export const thisIsAModule = true; // <-- definitely in a module

declare global {
    var foo: string;
}

After that, you should be able to access globalThis.foo as desired:

globalThis.foo = "bar"; // no error

Playground link to code

jcalz
  • 264,269
  • 27
  • 359
  • 360