Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    }
}
like image 852
AlexR Avatar asked Jan 02 '13 08:01

AlexR


2 Answers

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);
    }
}
like image 107
Fenton Avatar answered Sep 29 '22 06:09

Fenton


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

like image 39
Kuba Bladek Avatar answered Sep 29 '22 04:09

Kuba Bladek