3

I want to set a global variable in react native. It is neccessary and seems like only option in my particular usecase. I'm using typescript with my project. The problem is typescript complains when I set something like global.foo = bar; with the error "Property 'foo' does not exist on type 'typeof globalThis'." I have tried to create a declaration file like this -

declare module NodeJS {
    export interface Global {
        foo: any;
    }
}

and also with some other methods that I found online for react native or NodeJS. None seem to be working. Do anyone have any idea why this is not working. I have declared other modules in the same fashion and they all are working except the global one. Why?

2 Answers2

1

You can cheat and do this:

(global as any).foo = bar;

And when you need to access it, also use (global as any).foo

Obviously it's a bad practice both from the type safety point of view, and polluting the global namespace, but you've said it was the only way for you case...

tromgy
  • 4,937
  • 3
  • 17
  • 18
  • I'm using **// @ts-ignore** and **// eslint-no-undef** with `(foo as typeof foo)` as of now. With this I'm getting typescript intellisense as well on the `foo` object. But I wanted to have a solution of this. Seems like I'm not finding any. – Sharique Khan Oct 31 '21 at 12:38
1

Have a look at this answer.

In short, things seems to have changed from TypeScript 3.4, globalThis is now used and with it NodeJS's global variable.

The answer for me was quite simple, in a *.d.ts file:

declare var foo: any

Which actually seems sensible; you're declaring a global type the same way you would if it was a global variable.

Jamie Robinson
  • 832
  • 10
  • 16