简体   繁体   中英

Using out of scope functions in Typescript

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.

So the question is how do I use window.srslyUsefulFunction in my own typescript file without creating a definition for it?

Example:

class MyClass {
    public MyMethod (id : string) : void {
        // do something 
        var result = window.srslyUsefulFunction(id);
        // do something (with the result)
    }
}

You can add the function to the Window interface and then use it in your TypeScript program:

interface Window {
    srslyUsefulFunction(id: number): void;
}

class MyClass {
    doSomething() {
        window.srslyUsefulFunction(1);
    }
}

I have simple workaround.

In index.html

function playIntro() {
        intro = new lib.intro();
        onlinePlayer.contentContainer.addChild(intro);
        stage.update();
    }

in my Main.ts I call it like that:

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

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!");
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM