Skip to main content

class-methods-use-this

Enforce that class methods utilize this.

🧱

This is an "extension" rule that replaces a core ESLint rule to work with TypeScript. See Rules > Extension Rules.

This rule extends the base class-methods-use-this rule from ESLint core. It adds support for ignoring override methods and/or methods on classes that implement an interface. It also supports auto-accessor properties.

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

Whether to ignore members marked with the override modifier. Default: false.

Example of correct code when ignoreOverrideMethods is set to true:

abstract class Base {
abstract method(): void;
abstract property: () => void;
}

class Derived extends Base {
override method() {}
override property = () => {};
}
Open in Playground

ignoreClassesThatImplementAnInterface

Whether to 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

Note that this option applies to all class members, not just those defined in the interface.

true

Examples of code when ignoreClassesThatImplementAnInterface is set to true:

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

'public-fields'

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

interface Base {
method(): void;
}

class Derived implements Base {
method() {}
property = () => {};

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

protected protectedMethod() {}
protected protectedProperty = () => {};
}
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.