在 TypeScript 中创建一个全局变量 [英] Create a global variable in TypeScript

查看:115
本文介绍了在 TypeScript 中创建一个全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中,我可以这样做:

In JavaScript I can just do this:

 something = 'testing';

然后在另一个文件中:

 if (something === 'testing')

并且它会定义something(只要它们以正确的顺序调用).

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

我似乎不知道如何在 TypeScript 中做到这一点.

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

这是我试过的.

在 .d.ts 文件中:

In a .d.ts file:

interface Window { something: string; }

然后在我的 main.ts 文件中:

Then in my main.ts file:

 window.something = 'testing';

然后在另一个文件中:

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

这是有效的.但是我希望能够丢失 window. 的一部分,并且让我的 something 成为全局的.有没有办法在 TypeScript 中做到这一点?

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?

(如果有人感兴趣,我真的想为我的应用程序设置日志记录.我希望能够从任何文件调用 log.Debug ,而不必导入和创建对象.)

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

推荐答案

好的,所以这可能比你所做的更丑陋,但无论如何......

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

但我也这样做...

你可以在纯 TypeScript 中做的是使用 eval 函数,如下所示:

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';")

然后你就可以做

if (something === 'testing')

这只不过是在 TypeScript 拒绝编译的情况下强制执行指令的一种黑客攻击,我们声明 var 以便 TypeScript 编译其余代码.

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.

这篇关于在 TypeScript 中创建一个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆