@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 selfUnexpected aliasing of this to local variable. = this;
setInterval(function () {
self.seconds++;
}, 1000);
}
}example.tsNo problems
class Timer {
seconds = 0;
start() {
setInterval(() => {
this.seconds++;
}, 1000);
}
}Options#
| Option | Default | What it does |
|---|---|---|
allowDestructuring | true | Allow 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 problemclass Timer {
seconds = 0;
report() {
const { seconds }Unexpected aliasing of members of this to local variables. = this;
return `${seconds}s`;
}
}With allowedNames: ["self"], only that is reported:
example.tswith
{ "allowedNames": ["self"] }1 problemclass Timer {
start() {
const self = this;
const thatUnexpected aliasing of this to local variable. = this;
return [self, that];
}
}