Vaccano Vaccano - 1 year ago 192
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
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
part of it and just have my
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
from any file without having to import and create objects.)

Answer Source

I found a way that works if I use javascript combined with typescript.


declare var log: log4javascript.Logger;


log = null;


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download