zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] @typescript-eslint/unbound-method

typescript method eslint
2023-09-14 09:00:42 时间

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',