2

I have some global variables that I inject into my React application with Webpack.

const globals = {
    BACKEND_URL: 'https://example.com',
    ENVIRONMENT: 'production',
    ...
};

export default globals;

I have injected them, but I would also like typescript to be able to pick them up automatically. Usually, you would map over types like this :

{ [P in globalKeys]: globalType[P] };

But I am not sure how to put that into the global context. Mapped types are only available on types, but Window is an interface.

They should be available in the global context (via implicit window), e.g.

const isProduction = ENVIRONMENT === "production";  // ENVIRONMENT is defined
Connor Low
  • 5,900
  • 3
  • 31
  • 52
Twiggeh
  • 1,030
  • 1
  • 12
  • 24
  • I'm afraid I don't understand what you're asking for. Could you provide a [mcve] someone could drop into a standalone IDE like [the TypeScript Playground](https://tsplay.dev/WPjPkN) that demonstrates your issue? Or maybe a link to an appropriately configured web IDE project that does so? If this is specific to React or Webpack you might want to tag the question as such; otherwise you might want to remove any implied dependencies of the question on them. – jcalz Sep 09 '21 at 15:51
  • 1
    Does this answer your question? [Create a global variable in TypeScript](https://stackoverflow.com/questions/38906359/create-a-global-variable-in-typescript) – Asher G. Sep 09 '21 at 17:01
  • Offhand, the only way I can think of doing this is adding each property of global to the `Window` interface individually as properties. You can spread an object onto an interface; interfaces are meant to be explicit. – Connor Low Sep 09 '21 at 17:14
  • _Sorry, **cannot** spread an object..._ @jcalz, if I understand correctly, he's asking how he can merge `typeof globals` with the interface `Window` since `globals` (again, I assume from the question) really is merged with `window` at runtime. The functionality is there; TS just isn't aware of it. – Connor Low Sep 09 '21 at 17:21
  • 1
    You can definitely use declaration merging to get stuff into `Window` (with a bit of juggling) like [this](https://tsplay.dev/NVKdGm), and that will let you write `window.ENVIRONMENT` but not just `ENVIRONMENT`. As far as I know there's no way to declare global variables without doing them one at a time. I can write any of this up as an answer I guess? – jcalz Sep 09 '21 at 18:36
  • @jcalz looked like the thing closest to what I would want, it doesn't really cover the whole usecase though. I would give you an upvote though :D I ended up just importing everything from a globals.ts file. – Twiggeh Sep 10 '21 at 08:57

0 Answers0