Search code examples
typescriptstrictwebix

Handle inner this inside callback function in strict mode


I got stuck with problem TS2683 while using webix(5.4.0) + typescript(3.1.1) in strict mode.

($$('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
      ...
}

error is:

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

I've read How to access the correct `this` inside a callback? But it seems, everything's about handling outer this, moreover I need to declare inner this type. So what should I do?


Solution

  • You need to add a type annotation to let the compiler know the type of this

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

    Ideally the attachEvent method should have specified the type of this in the callback type but since it does not you need to specify it manually.