10

I declare a global variable in typescript something like: global.test = "something" I try to do that I get the error property ‘test’ does not exist on type ‘Global’.

Jheorge
  • 103
  • 1
  • 1
  • 4
  • I've seen people do it a few different ways. You can setup global variables inside of a .ts file that just exports each variable. Or you can put them in a file that looks like the environment variables file and import that. You'll still have to import the globals file whenever you want to use the variables inside of it, though. – Joshua Terrill May 23 '17 at 03:40
  • If it is a browser based typescript you can try window.test="something" – skvsree May 23 '17 at 03:41
  • 3
    Duplicate of [this](https://stackoverflow.com/questions/38906359/create-a-global-variable-in-typescript) SO question. – Jeroen Heier May 23 '17 at 03:56
  • Why does this question (a duplicate of a much better SO entry) show up more and instead of the better one? The only reason I found the original is because @JeroenHeier made that comment. Just the way web search works I guess. :| – raddevus May 24 '19 at 18:57

4 Answers4

17

I try to do that I get the error property ‘test’ does not exist on type ‘Global’.

Create a file globals.d.ts with

interface Global {
 test: string;
}

More

Declaration files : https://basarat.gitbook.io/typescript/docs/types/ambient/d.ts.html

basarat
  • 261,912
  • 58
  • 460
  • 511
8

in global.ts

export namespace Global {
    export var test: string = 'Hello World!';
}

in your.ts

import { Global } from "./global";
console.log(Global.test)
nsnze
  • 346
  • 2
  • 9
  • 4
    This is not actually global, since the import is still necessary, the answer from @basarat is actually global. – Rosdi Kasim Feb 11 '19 at 03:44
2

Inside a global.d.ts definition file

type MyProfileGlobal = (name: string,age:number) => void

Config.tsx file

In React:

interface Window {
  myProfileFun: MyProfileGlobal
}

In NodeJS:

declare module NodeJS {
  interface Global {
    myProfileFun: MyProfileGlobal
  }
}

Now you declare the root variable (that will actually live on window or global)

declare const myProfileFun: MyProfileGlobal;

Use it elsewhere in code, with either[Add data]:

global/* or window */.myProfileFun("Sagar",28);

myProfileFun("Sagar",28);

Use it elsewhere in code, with either[Get data]:

global/* or window */.myProfileFun= function (name: string,age:number) {
      console.log("Name: ", name);console.log("Age: ", name);
 };
Sagar Mistry
  • 131
  • 11
0

The simplest way to declare a global variable in typescript:

// foo.ts
interface IData {
    test: string;
}
declare global {
    var someVar: IData;
}

Now, in any other file in the project:

// bar.ts
import 'foo'
somVar.test = 'Yes !!!!'
Nati Kamusher
  • 533
  • 5
  • 9