class-methods-use-this
Enforce that class methods utilize
this
.
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
此规则扩展了基本 eslint/class-methods-use-this
规则。
它添加了对忽略 override
方法或实现接口的类上的方法的支持。
英: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.
选项
该规则添加了以下选项:
英: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
使规则忽略任何显式标记为 override
的类成员。
英:Makes the rule to ignores any class member explicitly marked with override
.
ignoreOverrideMethods
设置为 true
时的正确代码示例:
英:Example of a correct code when ignoreOverrideMethods
is set to true
:
class X {
override method() {}
override property = () => {};
}
Open in PlaygroundignoreClassesThatImplementAnInterface
使规则忽略在 implements
类型的类中定义的类成员。
如果指定,它可以是:
英:Makes the rule ignore class members that are defined within a class that implements
a type.
If specified, it can be either:
true
: 忽略所有实现接口的类'public-fields'
: 仅忽略实现接口的类的公共字段
值得注意的是,此选项不仅适用于接口中定义的成员,因为这需要类型信息。
英: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
ignoreClassesThatImplementAnInterface
设置为 true
时的正确代码示例:
英:Example of a correct code when ignoreClassesThatImplementAnInterface
is set to true
:
class X implements Y {
method() {}
property = () => {};
}
Open in Playground'public-fields'
ignoreClassesThatImplementAnInterface
设置为 'public-fields'
时的错误代码示例:
英:Example of a 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 Playgroundclass X implements Y {
method() {}
property = () => {};
}
Open in Playground何时不使用它
如果你的项目以 TypeScript 建模困难的方式动态更改 this
范围,则此规则可能不可行。
你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
英: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.
如何使用
module.exports = {
"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"
}
};
选项
参见 eslint/class-methods-use-this
选项。
资源
摘自 ❤️ ESLint 内核