explicit-member-accessibility
要求类属性和方法上有显式可访问性修饰符.
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
TypeScript 允许在类成员前面放置显式 public
、protected
和 private
可访问性修饰符。修饰符仅存在于类型系统中,仅用于描述允许谁访问这些成员。
¥TypeScript allows placing explicit public
, protected
, and private
accessibility modifiers in front of class members.
The modifiers exist solely in the type system and just serve to describe who is allowed to access those members.
去掉可访问性修饰符可以减少读取和写入的代码。成员默认为 public
。
¥Leaving off accessibility modifiers makes for less code to read and write.
Members are public
by default.
但是,在具有许多类的代码库中添加显式可访问性修饰符有助于强制执行成员的适当隐私。一些开发者还发现,为了代码的可读性,保持成员公开的明确性更好。
¥However, adding in explicit accessibility modifiers can be helpful in codebases with many classes for enforcing proper privacy of members. Some developers also find it preferable for code readability to keep member publicity explicit.
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
"@typescript-eslint/explicit-member-accessibility": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/explicit-member-accessibility": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
此规则旨在使代码更具可读性,并且更明确地说明谁可以使用哪些属性 。
¥This rule aims to make code more readable and explicit about who can use which properties.
选项
该规则接受以下选项:
type AccessibilityLevel =
/** 始终需要访问器。 */
| 'explicit'
/** 永远不要检查是否有访问器。 */
| 'off'
/** 除公共外,要求访问器。 */
| 'no-public';
type Options = [
{
/** 需要存在或不存在哪些可访问性修饰符。 */
accessibility?: AccessibilityLevel;
/** 可以忽略的特定方法名称。 */
ignoredMethodNames?: string[];
/** 更改特定类型的类成员所需的可访问性修饰符。 */
overrides?: {
accessors?: AccessibilityLevel;
constructors?: AccessibilityLevel;
methods?: AccessibilityLevel;
parameterProperties?: AccessibilityLevel;
properties?: AccessibilityLevel;
};
},
];
const defaultOptions: Options = [{ accessibility: 'explicit' }];
¥Options
在混合 JS/TS 代码库中进行配置
¥Configuring in a mixed JS/TS codebase
如果你正在处理一个代码库,在其中对非 TypeScript 代码进行 lint(即 .js
/.mjs
/.cjs
/.jsx
),则应确保使用 ESLint overrides
仅在 .ts
/.mts
/.cts
/.tsx
文件上启用规则。如果你不这样做,那么你将在 .js
/.mjs
/.cjs
/.jsx
文件中报告无法修复的 lint 错误。
¥If you are working on a codebase within which you lint non-TypeScript code (i.e. .js
/.mjs
/.cjs
/.jsx
), you should ensure that you should use ESLint overrides
to only enable the rule on .ts
/.mts
/.cts
/.tsx
files. If you don't, then you will get unfixable lint errors reported within .js
/.mjs
/.cjs
/.jsx
files.
{
"rules": {
// disable the rule for all files
"@typescript-eslint/explicit-member-accessibility": "off",
},
"overrides": [
{
// enable the rule specifically for TypeScript files
"files": ["*.ts", "*.mts", "*.cts", "*.tsx"],
"rules": {
"@typescript-eslint/explicit-member-accessibility": "error",
},
},
],
}