Skip to main content

no-this-alias

Disallow aliasing this.

This rule prohibits assigning variables to this.

Attributes

  • Included in configs
    • ✅ Recommended
    • 🔒 Strict
  • Fixable
    • 🔧 Automated Fixer
    • 💡 Suggestion Fixer
  • 💭 Requires type information

Rule Details​

Assigning a variable to this instead of properly using arrow lambdas may be a symptom of pre-ES6 practices or not managing scope well.

Instead of storing a reference to this and using it inside a function () {:

const self = this;
>
setTimeout(function () {
self.doWork();
});

Use () => arrow lambdas, as they preserve this scope for you:

setTimeout(() => {
this.doWork();
});

Examples of incorrect code for this rule:

(see the rationale above)

Examples of correct code for this rule:

(see the rationale above)

Options​

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-this-alias": "error"
}
};

When Not To Use It​

This rule accepts an options object with the following properties:

interface Options {
/**
* Whether to ignore destructurings, such as `const { props, state } = this`.
*/
allowDestructuring?: boolean;
/**
* Names to ignore, such as ["self"] for `const self = this;`.
*/
allowedNames?: string[];
}

const defaultOptions: Options = [
{ allowDestructuring: true, allowedNames: [] },
];

If you need to assign this to variables, you shouldn’t use this rule.

Resources​