Vaccano Vaccano - 19 days ago 5
TypeScript Question

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

Answer

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.