Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript error accessing globalThis property

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?

like image 928
brewster Avatar asked Aug 26 '26 22:08

brewster


1 Answers

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

like image 167
jcalz Avatar answered Aug 28 '26 13:08

jcalz