no-dupe-class-members

禁止重复的类成员

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

如果类成员中有同名的声明,最后一个声明会默默地覆盖其他声明。它可能会导致意外行为。

¥If there are declarations of the same name in class members, the last declaration overwrites other declarations silently. It can cause unexpected behaviors.

class Foo {
  bar() { console.log("hello"); }
  bar() { console.log("goodbye"); }
}

const foo = new Foo();
foo.bar(); // goodbye

规则详情

¥Rule Details

该规则旨在标记类成员中重复名称的使用。

¥This rule is aimed to flag the use of duplicate names in class members.

示例

¥Examples

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-dupe-class-members: "error"*/

class A {
  bar() { }
  bar() { }
}

class B {
  bar() { }
  get bar() { }
}

class C {
  bar;
  bar;
}

class D {
  bar;
  bar() { }
}

class E {
  static bar() { }
  static bar() { }
}

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-dupe-class-members: "error"*/

class A {
  bar() { }
  qux() { }
}

class B {
  get bar() { }
  set bar(value) { }
}

class C {
  bar;
  qux;
}

class D {
  bar;
  qux() { }
}

class E {
  static bar() { }
  bar() { }
}

此规则还支持 TypeScript 类型语法。它支持 TypeScript 的方法重载定义。

¥This rule additionally supports TypeScript type syntax. It has support for TypeScript’s method overload definitions.

此规则的正确 TypeScript 代码示例:

¥Examples of correct TypeScript code for this rule:

/* eslint no-dupe-class-members: "error" */

class A {
	foo(value: string): void;
	foo(value: number): void;
	foo(value: string | number) {} // ✅ This is the actual implementation.
}

何时不使用

¥When Not To Use It

此规则不应在 ES3/5 环境中使用。

¥This rule should not be used in ES3/5 environments.

在 ES2015 (ES6) 或更高版本中,如果你不想在类成员中收到重复名称的通知,你可以安全地禁用此规则。

¥In ES2015 (ES6) or later, if you don’t want to be notified about duplicate names in class members, you can safely disable this rule.

由 TypeScript 处理

使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。

版本

此规则是在 ESLint v1.2.0 中引入。

资源