'how can I declare a global variable in typescript

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’.



Solution 1:[1]

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

Solution 2:[2]

in global.ts

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

in your.ts

import { Global } from "./global";
console.log(Global.test)

Solution 3:[3]

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);
 };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 nsnze
Solution 3 Sagar Mistry