打字稿绑定问题

时间:2013-10-31 09:20:20

标签: javascript jquery prototype typescript

我正在尝试将这个函数从原型移植到打字稿中的jquery:

    onFailure: function(xhr) {
    // Get options
    var opts = this;

    // Show result
    var msgBox = opts.msgBox ? opts.msgBox : opts.client.options.msgBox;  
    if (msgBox && !opts.onFailure) {
        msgBox.showError('Communicatie fout.');
    }

    // Handle onFailure callback
    if (opts.onFailure) {
        opts.onFailure.bind(opts.client)(xhr);
    }
    else if (opts.options && opts.options.onFailure) {
        opts.options.onFailure.bind(opts.client)(xhr);
    }

    // Fire event
    opts.client.failureCb.fire('failure');
},

这是移植的代码:

        onFailure(xhr){
            // Get options
            var opts = this;

            // Show result
            var msgBox = opts.msgBox ? opts.msgBox : opts.client.options.msgBox;
            if (msgBox && !opts.onFailure) {
                msgBox.showError('Communicatie fout.');
            }

            // Handle onFailure callback
            if (opts.onFailure) {
                opts.onFailure(opts.client)(xhr);
            }
            else if (opts.options && opts.options.onFailure) {
                opts.options.onFailure.bind(opts.client)(xhr);
            }

            // Fire event
            opts.client.failureCb.fire('failure');
        }

如你所见,它并没有太大的不同。然而问题来自typescript编译器:

  

错误TS2094:属性'bind'在'null'类型的值

上不存在

如何正确移植到jquery?

感谢。

1 个答案:

答案 0 :(得分:1)

发生这种情况的唯一原因是因为typescript根据你所写的内容推断了类型:

var opts = {
    options:{
        onFailure: null
    }
} 

// The property 'bind' does not exist on value of type 'null'
opts.options.onFailure.bind(); 

您可以通过明确键入变量any来覆盖此行为:

var opts:any = {
    options:{
        onFailure: null
    }
} 

// no more error
opts.options.onFailure.bind(); 

这将删除编译错误,但我怀疑这个编译错误可能指向代码中的有效逻辑错误。