在 Typescript 中使用超出范围的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14118878/
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
Using out of scope functions in Typescript
提问by AlexR
I think this has been addressed somewhere, at some point, just for the life of me I can't remember so here's my question:
我认为这已经在某处解决了,在某个时候,只是为了我的生活,我不记得了,所以这是我的问题:
I'm doing some javascript work that will be loaded into an existing application. This application has crap loads of functions available and hardly any of it is known to me except some that I want to actually use. So lets say that I know for a fact that window.srslyUsefulFunction will be available to me and I don't care much for porting this in to a typescript definition.
我正在做一些将加载到现有应用程序中的 javascript 工作。这个应用程序有大量可用的功能,除了一些我想实际使用的功能外,我几乎不知道其中的任何功能。所以可以说我知道 window.srslyUsefulFunction 对我可用的事实,我不太关心将它移植到打字稿定义中。
So the question is how do I use window.srslyUsefulFunction in my own typescript file without creating a definition for it?
所以问题是如何在我自己的打字稿文件中使用 window.srslyUsefulFunction 而不为其创建定义?
Example:
例子:
class MyClass {
public MyMethod (id : string) : void {
// do something
var result = window.srslyUsefulFunction(id);
// do something (with the result)
}
}
采纳答案by Fenton
You can add the function to the Window
interface and then use it in your TypeScript program:
您可以将该函数添加到Window
界面中,然后在您的 TypeScript 程序中使用它:
interface Window {
srslyUsefulFunction(id: number): void;
}
class MyClass {
doSomething() {
window.srslyUsefulFunction(1);
}
}
回答by Kuba Bladek
I have simple workaround.
我有简单的解决方法。
In index.html
在 index.html
function playIntro() {
intro = new lib.intro();
onlinePlayer.contentContainer.addChild(intro);
stage.update();
}
in my Main.ts I call it like that:
在我的 Main.ts 我这样称呼它:
private onClick(event): void {
if (window.hasOwnProperty('playIntro')) {
window['playIntro'].call();
}
}
So... if you want to call "blind" js function from global scope, just use window["foo"].call();
所以......如果你想从全局范围调用“盲”js函数,只需使用 window["foo"].call();
回答by Cerbrus
Check if the function exists. If it doesn't, declare it:
检查函数是否存在。如果没有,请声明它:
if(!window.hasOwnProperty('srslyUsefulFunction')
|| typeof window['srslyUsefulFunction'] !== "function"){
window['srslyUsefulFunction'] = function(){
console.log("You're only running a dummy implementation of srslyUsefulFunction here!");
};
}