typescript 在模块内部调用全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13252225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a global variable inside module
提问by user1027303
I have a typescript file called Projects.ts
that I want to reference a global variable declared in a bootstrap plugin called bootbox.js
.
我有一个名为的打字稿文件Projects.ts
,我想引用在名为bootbox.js
.
I want to access a variable called bootbox
from within a TypeScript classes.
我想访问bootbox
从 TypeScript 类中调用的变量。
Is it possible?
是否可以?
回答by Fenton
You need to tell the compiler it has been declared:
您需要告诉编译器它已被声明:
declare var bootbox: any;
If you have better type information you can add that too, in place of any
.
如果你有更好的类型信息,你也可以添加它,代替any
.
回答by Himanshu Arora
For those who didn't know already, you would have to put the declare
statement outside your class
just like this:
对于那些还不知道的人,您必须像这样将declare
语句放在您的外面class
:
declare var Chart: any;
@Component({
selector: 'my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent {
//you can use Chart now and compiler wont complain
private color = Chart.color;
}
In TypeScript
the declare keyword is used where you want to define a variable that may not have originated from a TypeScript
file.
在TypeScript
你想要定义一个可能不是来自TypeScript
文件的变量的地方使用 declare 关键字。
It is like you tell the compiler that, I know this variable will have a value at runtime, so don't throw a compilation error.
就像你告诉编译器一样,我知道这个变量在运行时会有一个值,所以不要抛出编译错误。
回答by Josh Wulf
If it is something that you reference but never mutate, then use const
:
如果它是您引用但从不变异的东西,则使用const
:
declare const bootbox;
回答by Prusdrum
Sohnee solutions is cleaner, but you can also try
Sohnee 解决方案更干净,但您也可以尝试
window["bootbox"]
回答by Krzysztof Grzybek
If You want to have a reference to this variable across the whole project, create somewhere d.ts
file, e.g. globals.d.ts
. Fill it with your global variables declarations, e.g.:
如果您想在整个项目中引用此变量,请创建某个d.ts
文件,例如globals.d.ts
. 用您的全局变量声明填充它,例如:
declare const BootBox: 'boot' | 'box';
Now you can reference it anywhere across the project, just like that:
现在你可以在整个项目的任何地方引用它,就像这样:
const bootbox = BootBox;
Here's an example.
这是一个例子。
回答by ser savv
Download the bootbox typings
下载引导箱类型
Then add a reference to it inside your .ts file.
然后在 .ts 文件中添加对它的引用。