@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:
[lint.rules]
"@typescript-eslint/no-invalid-this" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"@typescript-eslint/no-invalid-this" = ["error", {
capIsConstructor = true,
}]Examples#
const button = {
label: "Save",
onClick() {
setTimeout(function () {
console.log(thisUnexpected this..label);
}, 100);
},
};const button = {
label: "Save",
onClick() {
setTimeout(() => {
console.log(this.label);
}, 100);
},
};interface Button {
label: string;
}
function describe(this: Button) {
return this.label;
}Options#
| Option | Default | What it does |
|---|---|---|
capIsConstructor | true | Treat a function with a name that starts with a capital letter as a constructor, where this is fine. |
function Timer() {
this.startedAt = Date.now();
}{ "capIsConstructor": false }1 problemfunction Timer() {
thisUnexpected 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.