AlexR
AlexR

Reputation: 305

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)
    }
}

Upvotes: 16

Views: 18675

Answers (3)

Kuba Bladek
Kuba Bladek

Reputation: 51

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

Upvotes: 5

Cerbrus
Cerbrus

Reputation: 72857

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

Upvotes: 1

Fenton
Fenton

Reputation: 250922

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

Upvotes: 18

Related Questions