Issue
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.)
Solution
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.
Answered By – tforgione
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0