Skip to main content

explicit-member-accessibility

Require explicit accessibility modifiers on class properties and methods.

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💡

此规则报告的一些问题可以通过编辑器 建议 手动修复。


TypeScript 允许在类成员前面放置显式的 publicprotectedprivate 可访问性修饰符。 修饰符仅存在于类型系统中,仅用于描述允许谁访问这些成员。

英: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.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/explicit-member-accessibility": "error"
}
};
在线运行试试这个规则 ↗

示例

此规则旨在使代码更具可读性,并且更明确地说明谁可以使用哪些属性。

英:This rule aims to make code more readable and explicit about who can use which properties.

选项

在混合 JS/TS 代码库中进行配置

如果你正在开发的代码库中包含 lint 非 TypeScript 代码(即 .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"
}
}
]
}

accessibility

该规则在默认状态下不需要配置,并且将强制每个类成员都具有可访问性修饰符。 如果你想允许一些隐式公共成员,那么你有以下选择:

英:This rule in its default state requires no configuration and will enforce that every class member has an accessibility modifier. If you would like to allow for some implicit public members then you have the following options:

{
accessibility: 'explicit',
overrides: {
accessors: 'explicit',
constructors: 'no-public',
methods: 'explicit',
properties: 'off',
parameterProperties: 'explicit'
}
}

请注意,上面是你可以使用的可能配置的示例 - 它不是默认配置。

英:Note the above is an example of a possible configuration you could use - it is not the default configuration.

如果未提供选项,以下模式将被视为不正确的代码:

英:The following patterns are considered incorrect code if no options are provided:

class Animal {
constructor(name) {
// No accessibility modifier
this.animalName = name;
}
animalName: string; // No accessibility modifier
get name(): string {
// No accessibility modifier
return this.animalName;
}
set name(value: string) {
// No accessibility modifier
this.animalName = value;
}
walk() {
// method
}
}
Open in Playground

使用默认选项 { accessibility: 'explicit' } 时,以下模式被认为是正确的:

英:The following patterns are considered correct with the default options { accessibility: 'explicit' }:

class Animal {
public constructor(
public breed,
name,
) {
// Parameter property and constructor
this.animalName = name;
}
private animalName: string; // Property
get name(): string {
// get accessor
return this.animalName;
}
set name(value: string) {
// set accessor
this.animalName = value;
}
public walk() {
// method
}
}
Open in Playground

当可访问性设置为 no-public [{ accessibility: 'no-public' }] 时,以下模式被认为是不正确的:

英:The following patterns are considered incorrect with the accessibility set to no-public [{ accessibility: 'no-public' }]:

class Animal {
public constructor(
public breed,
name,
) {
// Parameter property and constructor
this.animalName = name;
}
public animalName: string; // Property
public get name(): string {
// get accessor
return this.animalName;
}
public set name(value: string) {
// set accessor
this.animalName = value;
}
public walk() {
// method
}
}
Open in Playground

当可访问性设置为 no-public [{ accessibility: 'no-public' }] 时,以下模式被认为是正确的:

英:The following patterns are considered correct with the accessibility set to no-public [{ accessibility: 'no-public' }]:

class Animal {
constructor(
protected breed,
name,
) {
// Parameter property and constructor
this.name = name;
}
private animalName: string; // Property
get name(): string {
// get accessor
return this.animalName;
}
private set name(value: string) {
// set accessor
this.animalName = value;
}
protected walk() {
// method
}
}
Open in Playground

overrides

可以通过三种方式使用覆盖。

英:There are three ways in which an override can be used.

  • 禁止对给定成员使用 public。
  • 当根允许隐式公共访问时强制执行显式成员访问
  • 禁用对给定成员类型的任何检查

禁止对指定成员使用 public

例如 [ { overrides: { constructors: 'no-public' } } ]

英:e.g. [ { overrides: { constructors: 'no-public' } } ]

对于示例覆盖,以下模式被认为是不正确的

英:The following patterns are considered incorrect with the example override

class Animal {
public constructor(protected animalName) {}
public get name() {
return this.animalName;
}
}
Open in Playground

对于示例覆盖,以下模式被认为是正确的

英:The following patterns are considered correct with the example override

class Animal {
constructor(protected animalName) {}
public get name() {
return this.animalName;
}
}
Open in Playground

要求给定成员具有显式可访问性

例如 [ { accessibility: 'no-public', overrides: { properties: 'explicit' } } ]

英:e.g. [ { accessibility: 'no-public', overrides: { properties: 'explicit' } } ]

对于示例覆盖,以下模式被认为是不正确的

英:The following patterns are considered incorrect with the example override

class Animal {
constructor(protected animalName) {}
get name() {
return this.animalName;
}
protected set name(value: string) {
this.animalName = value;
}
legs: number;
private hasFleas: boolean;
}
Open in Playground

对于示例覆盖,以下模式被认为是正确的

英:The following patterns are considered correct with the example override

class Animal {
constructor(protected animalName) {}
get name() {
return this.animalName;
}
protected set name(value: string) {
this.animalName = value;
}
public legs: number;
private hasFleas: boolean;
}
Open in Playground

例如 [ { accessibility: 'off', overrides: { parameterProperties: 'explicit' } } ]

英:e.g. [ { accessibility: 'off', overrides: { parameterProperties: 'explicit' } } ]

以下代码被认为是不正确的示例覆盖

英:The following code is considered incorrect with the example override

class Animal {
constructor(readonly animalName: string) {}
}
Open in Playground

通过示例覆盖,以下代码模式被认为是正确的

英:The following code patterns are considered correct with the example override

class Animal {
constructor(public readonly animalName: string) {}
}

class Animal {
constructor(public animalName: string) {}
}

class Animal {
constructor(animalName: string) {}
}
Open in Playground

例如 [ { accessibility: 'off', overrides: { parameterProperties: 'no-public' } } ]

英:e.g. [ { accessibility: 'off', overrides: { parameterProperties: 'no-public' } } ]

以下代码被认为是不正确的示例覆盖

英:The following code is considered incorrect with the example override

class Animal {
constructor(public readonly animalName: string) {}
}
Open in Playground

通过示例覆盖,以下代码被认为是正确的

英:The following code is considered correct with the example override

class Animal {
constructor(public animalName: string) {}
}
Open in Playground

禁用对给定成员类型的任何检查

例如 [{ overrides: { accessors : 'off' } } ]

英:e.g. [{ overrides: { accessors : 'off' } } ]

由于不对被重写的成员类型执行任何检查,因此该成员类型允许所有可见性排列

英:As no checks on the overridden member type are performed all permutations of visibility are permitted for that member type

对于给定的配置,以下模式被认为是不正确的

英:The follow pattern is considered incorrect for the given configuration

class Animal {
constructor(protected animalName) {}
public get name() {
return this.animalName;
}
get legs() {
return this.legCount;
}
}
Open in Playground

对于示例覆盖,以下模式被认为是正确的

英:The following patterns are considered correct with the example override

class Animal {
public constructor(protected animalName) {}
public get name() {
return this.animalName;
}
get legs() {
return this.legCount;
}
}
Open in Playground

ignoredMethodNames

如果你想忽略某些特定方法,可以通过指定方法名称来实现。 请注意,此选项不关心上下文,并且将忽略具有这些名称的每个方法,这可能导致它丢失某些情况。 你应该谨慎使用这个。 例如 [ { ignoredMethodNames: ['specificMethod', 'whateverMethod'] } ]

英:If you want to ignore some specific methods, you can do it by specifying method names. Note that this option does not care for the context, and will ignore every method with these names, which could lead to it missing some cases. You should use this sparingly. e.g. [ { ignoredMethodNames: ['specificMethod', 'whateverMethod'] } ]

class Animal {
get specificMethod() {
console.log('No error because you specified this method on option');
}
get whateverMethod() {
console.log('No error because you specified this method on option');
}
public get otherMethod() {
console.log('This method comply with this rule');
}
}
Open in Playground

何时不使用它

如果你认为默认为 public 是一个不错的默认设置,那么你应该考虑使用 no-public 设置。 如果你想混合隐式和显式公共成员,则可以禁用此规则。

英:If you think defaulting to public is a good default, then you should consider using the no-public setting. If you want to mix implicit and explicit public members then you can disable this rule.

但是,请记住,不一致的风格可能会损害项目的可读性。 我们建议为此规则选择一个最适合你的项目的选项。

英:However, keep in mind that inconsistent style can harm readability in a project. We recommend picking a single option for this rule that works best for your project.

进一步阅读

选项

该规则接受以下选项

type AccessibilityLevel =
/** Always require an accessor. */
| 'explicit'
/** Never check whether there is an accessor. */
| 'off'
/** Require an accessor except when public. */
| 'no-public';

type Options = [
{
accessibility?: AccessibilityLevel;
ignoredMethodNames?: string[];
overrides?: {
accessors?: AccessibilityLevel;
constructors?: AccessibilityLevel;
methods?: AccessibilityLevel;
parameterProperties?: AccessibilityLevel;
properties?: AccessibilityLevel;
};
},
];

const defaultOptions: Options = [{ accessibility: 'explicit' }];

资源