[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',
相关文章
- [Typescript] Global Scope
- [Typescript 4.9] Satisfies operator
- [Typescript] 25. Medium - Trim Left
- [Typescript] Convert a js project to typescript
- [Typescript] Making TypeScript Stick - 6 - infer, build a ConstructorArg Type
- [TypeScript] Make typescript stick - 2
- [Typescript] Use the Nullish Coalescing Operator in TypeScript (isNil)
- [Typescript] Performance Bundling and tslib
- [Typescript] Simplify iteration of custom data structures in TypeScript with iterators (backwards iteration with for ... of.. loop)
- [Typescript] Make TypeScript Class Usage Safer with Strict Property Initialization
- [RxJS] Add debug method to Observable in TypeScript
- [Typescript] Creating Chainable Method Abstractions with Generics and the Builder Pattern - 05
- [Typescript] Constraining Types for Anything but null or undefined (T extends {})
- [Typescript] Tips: Use assertion functions inside classes
- [React Typescript 2022] Type a Radio Button Component in React using TypeScript
- [Typescript] Perform null Checks with Assertion Functions
- [Typescript] Ignore Null or Undefined Values with TypeScript Non-Null Assertion Operator
- [Typescript] Exclude Properties from a Type in TypeScript (Omit)
- [TypeScript] Represent Non-Primitive Types with TypeScript’s object Type
- [Typescript] Generics using TypeScript
- TypeScript class 的静态成员变量
- TypeScript里get属性的实现
- SAP UI5 未来发展的趋势之一:拥抱 TypeScript
- 实现一个自动生成typescript类型声明的工具