[typescript] Create a global variable in TypeScript

In JavaScript I can just do this:

 something = 'testing';

And then in another file:

 if (something === 'testing')

and it will have something be defined (as long as they were called in the correct order).

I can't seem to figure out how to do that in TypeScript.

This is what I have tried.

In a .d.ts file:

interface Window { something: string; }

Then in my main.ts file:

 window.something = 'testing';

then in another file:

 if (window.something  === 'testing')

And this works. But I want to be able to lose the window. part of it and just have my something be global. Is there a way to do that in TypeScript?

(In case someone is interested, I am really trying to setup my logging for my application. I want to be able to call log.Debug from any file without having to import and create objects.)

This question is related to typescript

The answer is


Okay, so this is probably even uglier that what you did, but anyway...

but I do the same so...

What you can do to do it in pure TypeScript, is to use the eval function like so :

declare var something: string;
eval("something = 'testing';")

And later you'll be able to do

if (something === 'testing')

This is nothing more than a hack to force executing the instruction without TypeScript refusing to compile, and we declare var for TypeScript to compile the rest of the code.


This is how I have fixed it:

Steps:

  1. Declared a global namespace, for e.g. custom.d.ts as below :
declare global {
    namespace NodeJS {
        interface Global {
            Config: {}
        }
    }
}
export default global;
  1. Map the above created a file into "tsconfig.json" as below:
"typeRoots": ["src/types/custom.d.ts" ]
  1. Get the above created global variable in any of the files as below:
console.log(global.config)

Note:

  1. typescript version: "3.0.1".

  2. In my case, the requirement was to set the global variable before boots up the application and the variable should access throughout the dependent objects so that we can get the required config properties.

Hope this helps!

Thank you


I needed to make lodash global to use an existing .js file that I could not change, only require.

I found that this worked:

import * as lodash from 'lodash';

(global as any)._ = lodash;

This is working for me, as described in this thread:

declare let something: string;
something = 'foo';

Inside a .d.ts definition file

type MyGlobalFunctionType = (name: string) => void

If you work in the browser, you add members to the browser's window context:

interface Window {
  myGlobalFunction: MyGlobalFunctionType
}

Same idea for NodeJS:

declare module NodeJS {
  interface Global {
    myGlobalFunction: MyGlobalFunctionType
  }
}

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

declare const myGlobalFunction: MyGlobalFunctionType;

Then in a regular .ts file, but imported as side-effect, you actually implement it:

global/* or window */.myGlobalFunction = function (name: string) {
  console.log("Hey !", name);
};

And finally use it elsewhere in the codebase, with either:

global/* or window */.myGlobalFunction("Kevin");

myGlobalFunction("Kevin");

I spent couple hours to figure out proper way to do it. In my case I'm trying to define global "log" variable so the steps were:

1) configure your tsconfig.json to include your defined types (src/types folder, node_modules - is up to you):

...other stuff...
"paths": {
  "*": ["node_modules/*", "src/types/*"]
}

2) create file src/types/global.d.ts with following content (no imports! - this is important), feel free to change any to match your needs + use window interface instead of NodeJS if you are working with browser:

/**
 * IMPORTANT - do not use imports in this file!
 * It will break global definition.
 */
declare namespace NodeJS {
    export interface Global {
        log: any;
    }
}

declare var log: any;

3) now you can finally use/implement log where its needed:

// in one file
global.log = someCoolLogger();
// in another file
log.info('hello world');
// or if its a variable
global.log = 'INFO'

As an addon to Dima V's answer this is what I did to make this work for me.

// First declare the window global outside the class

declare let window: any;

// Inside the required class method

let globVarName = window.globVarName;


I'm using this:

interface Window {
    globalthing: any;
}

declare var globalthing: any;

im using only this

import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;

globalThis is the future.

First, TypeScript files have two kinds of scopes

global scope

If your file hasn't any import or export line, this file would be executed in global scope that all declaration in it are visible outside this file.

So we would create global variables like this:

// xx.d.ts
declare var age: number

// or 
// xx.ts
// with or without declare keyword
var age: number

// other.ts
globalThis.age = 18 // no error

All magic come from var. Replace var with let or const won't work.

module scope

If your file has any import or export line, this file would be executed within its own scope that we need to extend global by declaration-merging.

// xx[.d].ts
declare global {
  var age: number;
}

// other.ts
globalThis.age = 18 // no error

You can see more about module in official docs


I found a way that works if I use JavaScript combined with TypeScript.

logging.d.ts:

declare var log: log4javascript.Logger;

log-declaration.js:

log = null;

initalize-app.ts

import './log-declaration.js';

// Call stuff to actually setup log.  
// Similar to this:
log = functionToSetupLog();

This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.

NOTE: I think this only works because I have the allowJs TypeScript option set to true.

If someone posts an pure TypeScript solution, I will accept that.