1

I have inherited a Typescript project (has .ts) but I? can't seem to workout how to create a Global variable in a Typescript file and access it another.

I am new to Typescript so please bear with me.

I am not using Angular - saw this link Typescript - Declare optional global variable

Any pointers highly appreciated

Ram
  • 527
  • 1
  • 10
  • 26
  • 1
    Does this answer your question? [Create a global variable in TypeScript](https://stackoverflow.com/questions/38906359/create-a-global-variable-in-typescript) – Kipras Melnikovas Nov 04 '20 at 17:50

1 Answers1

0

It depends on which runtime you are using typescript (eg: nodejs or browser)

NodeJS runtime

You have to export and import your variable.

// a.ts
export const foo = "bar";
// b.ts
import { foo } from 'a.ts';

Browser runtime

You can use the global object window

window.foo = "bar"

You can also use export and import but in this case you have to build your code with a builder (webpacker, rollup and so on)

Since typescript 3.4, you can also use globalThis on both runtimes: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#type-checking-for-globalthis

Alexandre
  • 1,940
  • 1
  • 14
  • 21