1

I'm brand new to typescript - having an issue with variables and scope.

I have 2 public methods, one requires a string. The first method calls the second, from within a jQuery click function (which means I can't use this.methodName anymore). I tried fixing the scope in a logical method but TS complains that:

Supplied Paramaters do not match any signature of call target. Could not select overload for 'call' expression.

    public test1() {
        //fix scope
        var scopeFix = () => this.test2;

        $("#test").click(function () {
            //this.test2("blah");
            //^^^ This doesn't work because "this." is used by jquery
            scopeFix("blah");
        });
    }

    public test2(testString:string) {
        alert(testString);
    }

I'm sure it's something silly (like me mixing JS and TS too much) - any ideas?

3
  • 1
    Use a local to store a reference to the this scope you need, jsfiddle.net/9DjGp Commented Jan 23, 2014 at 18:02
  • So close! Thanks mate. Commented Jan 23, 2014 at 18:20
  • Sure, it's a common question. Nothing to do with typescript though. The typescript error is because the scopeFix function is a paramterless function that returns a function, so your call site is wrong, it should be more like fixScope()('blah'); Commented Jan 23, 2014 at 18:22

1 Answer 1

2

In TypeScript you can do this:

public test1() {
    $("#test").click(() => {
        this.test2("blah");
    });
}

Note the () => {} syntax. To give you an idea of what this is doing, check out the compiled JavaScript:

YourClass.prototype.test1 = function () {
    var _this = this;

    $("#test").click(function () {
        _this.test2("blah");
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.