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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.