@typescript-eslint/no-invalid-this

Disallow this where its value is undefined

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

In a module, this is undefined at the top level and in a plain function that's called without an object. Reading this.label there throws a TypeError. The usual cause is a callback written with function inside a method. It doesn't get the method's this.

this is fine in methods, class fields, constructors, and arrow functions inside them. It's also fine in a function that declares a this parameter, and in a function that gets its this from .bind(), .call() or .apply().

Configure#

Off by default. To turn it on:

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

Every option, set to its default:

bunfig.toml
[lint.rules]
"@typescript-eslint/no-invalid-this" = ["error", {
  capIsConstructor = true,
}]

Examples#

example.ts1 problem
const button = {
  label: "Save",
  onClick() {
    setTimeout(function () {
      console.log(this.label);
    }, 100);
  },
};
example.tsNo problems
const button = {
  label: "Save",
  onClick() {
    setTimeout(() => {
      console.log(this.label);
    }, 100);
  },
};
example.tsNo problems
interface Button {
  label: string;
}

function describe(this: Button) {
  return this.label;
}

Options#

OptionDefaultWhat it does
capIsConstructortrueTreat a function with a name that starts with a capital letter as a constructor, where this is fine.
example.tsNo problems
function Timer() {
  this.startedAt = Date.now();
}
example.tswith { "capIsConstructor": false }1 problem
function Timer() {
  this.startedAt = Date.now();
}

When not to use it#

With strict or noImplicitThis in tsconfig.json, TypeScript already rejects a this that has no type, which covers most of these reports.