[Typescript] @typescript-eslint/unbound-method

It is useful to enable 

'@typescript-eslint/unbound-method': 'error',

because this kind of error is related to this keyword, sometime it is hard to notice during code review.

Avoid referencing unbound methods which may cause unintentional scoping of `this`.

If your function does not access `this`, you can annotate it with `this: void`, or consider using an arrow function instead.

class Endpoint {
 sendMessage() {
   ...
   this.sendEncodeMessage()
 }
    
 private sendEncodedMessage() {
  ...
 }
}
    
// Consumer
const {sendMessage} = endpoint; // instance of endpoint

// if you call sendMessage(), this keyword inside of function is undefined

 

Fix:

class Endpoint {
 sendMessage = () => {
   ...
   this.sendEncodeMessage()
 }
    
 private sendEncodedMessage = () => {
  ...
 }
}
    
// Consumer
const {sendMessage} = endpoint; // instance of endpoint

sendMessage() // works!

 

So be careful when using destructing syntax of a function call!

To avoid this kind of mistake, you can enable '@typescript-eslint/unbound-method': 'error',

posted @ 2022-12-15 20:39  Zhentiw  阅读(555)  评论(0编辑  收藏  举报