【问题标题】:Handle inner this inside callback function in strict mode以严格模式处理内部 this 内部回调函数
【发布时间】:2018-10-11 14:06:45
【问题描述】:

在严格模式下使用 webix(5.4.0) + typescript(3.1.1) 时遇到问题 TS2683。

($$('DATE') as webix.ui.datepicker)attachEvent('onChange', function() {
      let val:any = this.getValue() // or let val = ... without any
      // this:this??? () = > not suit for me, btw
      ...
}

错误是:

'this' implicity has type 'any' because it doesn't have a type annotation.

我读过How to access the correct `this` inside a callback? 但看起来,一切都是关于处理外部这个,而且我需要声明内部这个类型。那我该怎么办?

【问题讨论】:

    标签: typescript strict webix


    【解决方案1】:

    需要添加类型注解让编译器知道this的类型

    ($$('DATE') as webix.ui.datepicker).attachEvent('onChange', function(this:webix.ui.datepicker) {
        let val:any = this.getValue()    
    });
    

    理想情况下,attachEvent 方法应该在回调类型中指定 this 的类型,但由于它不需要您手动指定。

    【讨论】:

      猜你喜欢
      • 2013-02-14
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      相关资源
      最近更新 更多