@typescript-eslint/no-this-alias

Disallow storing this in a variable

warn by default

Also called typescript-eslint/no-this-alias, typescript/no-this-alias

const self = this is a way to reach the outer this from a function callback, which has its own this. An arrow function doesn't, so inside it this is still the outer one. With an arrow function you don't need the extra variable, and nobody can mix up self and this.

This rule is on by default in TypeScript files.

Configure#

On by default as a warning. To turn it off:

bunfig.toml
[lint.rules]
"@typescript-eslint/no-this-alias" = "off" # or "error"

Every option, set to its default:

bunfig.toml
[lint.rules]
"@typescript-eslint/no-this-alias" = ["warn", {
  allowDestructuring = true,
  allowedNames = [], # list of strings
}]

Examples#

example.ts1 problem
class Timer {
  seconds = 0;

  start() {
    const self = this;
    setInterval(function () {
      self.seconds++;
    }, 1000);
  }
}
example.tsNo problems
class Timer {
  seconds = 0;

  start() {
    setInterval(() => {
      this.seconds++;
    }, 1000);
  }
}

Options#

OptionDefaultWhat it does
allowDestructuringtrueAllow taking properties out of this: const { seconds } = this.
allowedNames[]Names of variables that may hold this.

Reported with allowDestructuring: false:

example.tswith { "allowDestructuring": false }1 problem
class Timer {
  seconds = 0;

  report() {
    const { seconds } = this;
    return `${seconds}s`;
  }
}

With allowedNames: ["self"], only that is reported:

example.tswith { "allowedNames": ["self"] }1 problem
class Timer {
  start() {
    const self = this;
    const that = this;
    return [self, that];
  }
}