tools icon indicating copy to clipboard operation
tools copied to clipboard

📎 Implement `noThisAlias`, @typescript-eslint/no-this-alias

Open Conaclos opened this issue 2 years ago • 7 comments

Description

Implement the recommended ESLint rule @typescript-eslint/no-this-alias.

Note that, we should accept restructuring assignment such as const { props, state } = this.

Conaclos avatar May 15 '23 13:05 Conaclos

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?

ematipico avatar May 15 '23 21:05 ematipico

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?

Conaclos avatar May 16 '23 11:05 Conaclos

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?

ematipico avatar May 16 '23 13:05 ematipico

In the example do you mean // do something with `self` ?

Conaclos avatar May 16 '23 16:05 Conaclos

Yeah sorry :)

ematipico avatar May 16 '23 19:05 ematipico

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. no this use inside the function body).
  • noUselessThisAlias: remove useless aliasing of this.

Conaclos avatar May 17 '23 12:05 Conaclos

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!

ematipico avatar May 17 '23 14:05 ematipico