tools
tools copied to clipboard
📎 Implement `noThisAlias`, @typescript-eslint/no-this-alias
Description
Implement the recommended ESLint rule @typescript-eslint/no-this-alias.
Note that, we should accept restructuring assignment such as const { props, state } = this.
I have mixed feelings about this rule. I don't know how the TS eslint rule works, but in the web there are valid cases where this rule could create noise.
Should the rule take in consideration those cases? What does this rule prevent?
I think that the main reason of the existence of this rule is to detect cases where () => this could be used instead of function() { self }. In this regard, we could opt for a more specific rule such as useArrowFunctionThis? And then accepting this aliasing in all other cases?
I think that the main reason of the existence of this rule is to detect cases where () => this could be used instead of function() { self }.
That's my main concern 😅
Given the following code:
class B {
foo() {
const self = this;
window.addEventListener('click', function(evt) {
// do something with `this`
})
}
}
How should the rule behave in this case? Suggesting a .bind? Doing nothing?
In the example do you mean // do something with `self` ?
Yeah sorry :)
In this case, the function should be replaced by an arrow lambda and self should be replaced by this.
Thinking a bit more about this rule, this could be decomposed into two rules:
useArrowFunction: suggest using arrow function instead of function expression when possible (i.e. nothisuse inside the function body).noUselessThisAlias: remove useless aliasing ofthis.
Actually, sorry. I was wrong. I meant this in the comment.
The event listener binds the scope of this to the element that triggered the event, and maybe the user needs it. Maybe they need to read information from the HTML element (not the evt) and save it in the class.
Thinking a bit more about this rule, this could be decomposed into two rules:
* `useArrowLambda`: suggest using arrow lambda instead of function lambda when possible (i.e. no `this` use inside the lambda). * `noUselessThisAlias`: remove useless aliasing of `this`.
I like your proposal very much! Narrow use cases, one rule for each one!