Skip to main content

class-methods-use-this

Enforce that class methods utilize this.

This rule extends the base eslint/class-methods-use-this rule. It adds support for ignoring override methods or methods on classes that implement an interface.

How to Use

eslint.config.mjs
export default tseslint.config({
rules: {
// Note: you must disable the base rule as it can report incorrect errors
"class-methods-use-this": "off",
"@typescript-eslint/class-methods-use-this": "error"
}
});

Try this rule in the playground ↗

Options

See eslint/class-methods-use-this's options.

This rule adds the following options:

interface Options extends BaseClassMethodsUseThisOptions {
ignoreOverrideMethods?: boolean;
ignoreClassesThatImplementAnInterface?: boolean | 'public-fields';
}

const defaultOptions: Options = {
...baseClassMethodsUseThisOptions,
ignoreOverrideMethods: false,
ignoreClassesThatImplementAnInterface: false,
};

ignoreOverrideMethods

Ignore members marked with the override modifier Default: false.

Makes the rule ignore any class member explicitly marked with override.

Example of a correct code when ignoreOverrideMethods is set to true:

class X {
override method() {}
override property = () => {};
}
Open in Playground

ignoreClassesThatImplementAnInterface

Makes the rule ignore class members that are defined within a class that implements a type Default: false.

If specified, it can be either:

  • true: Ignore all classes that implement an interface
  • 'public-fields': Ignore only the public fields of classes that implement an interface

It's important to note that this option does not only apply to members defined in the interface as that would require type information.

true

Example of correct code when ignoreClassesThatImplementAnInterface is set to true:

class X implements Y {
method() {}
property = () => {};
}
Open in Playground

'public-fields'

Example of incorrect code when ignoreClassesThatImplementAnInterface is set to 'public-fields':

class X implements Y {
method() {}
property = () => {};

private privateMethod() {}
private privateProperty = () => {};

protected privateMethod() {}
protected privateProperty = () => {};
}
Open in Playground

When Not To Use It

If your project dynamically changes this scopes around in a way TypeScript has difficulties modeling, this rule may not be viable to use. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

Resources

Taken with ❤️ from ESLint core.