[Typescript] @typescript-eslint/unbound-method
typescript method eslint
2023-09-14 08:59:11 时间
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',
相关文章
- [Typescript] 77. Easy - Unshift
- [Typescript] 14. Easy - Parameters
- [Typescript] Making TypeScript Stick - 3
- [React Typescript 2022] Type a Radio Button Component in React using TypeScript
- [Typescript] Dynamic types: Use TypeScript's Mapped Types and Template Literal Types Together
- [Typescript] Statically Type Unknown Values with TypeScript's unknown Type
- [Typescript] Ignore Null or Undefined Values with TypeScript Non-Null Assertion Operator
- [Typescript] Make your optional fields required in TypeScript
- [TypeScript] Export public types from your library
- [Typescript] Sorting arrays in TypeScript
- [RxJS] Add debug method to Observable in TypeScript
- [TypeScript] 1. Catching JavaScript Mistakes with TypeScript
- [Typescript 4.9] TypeScript 4.9: satisfies operator
- [Typescript] 44. Medium - Drop char
- [Typescript Challenges] 10. Medium - Include
- [Typescript Challenges] 9. Easy - Concat
- [React Typescript 2022] Refactor a React Component using TypeScript
- [Typescript] Create Type From Any Given Data in TypeScript
- [Typescript] Extend Functionality of a TypeScript Class with Decorators
- [Tools] Unlock TypeScript's Features in Vanilla JS with @ts-check and JSDoc
- [TypeScript] Typescript Interfaces vs Aliases Union & Intersection Types
- [RxJS] Add debug method to Observable in TypeScript
- TypeScript学习笔记