no-useless-computed-key
禁止在对象和类中使用不必要的计算属性键
对于诸如以下的字面量使用计算属性是不必要的
const foo = {["a"]: "b"};
代码可以重写为
const foo = {"a": "b"};
规则详情
此规则禁止不必要地使用计算属性键。
此规则的错误代码示例
在 Playground 中打开
/*eslint no-useless-computed-key: "error"*/
const a = { };
const b = { };
const c = { };
const d = { };
const e = { };
const { } = obj;
const { } = obj;
class Foo {
}
此规则的正确代码示例
在 Playground 中打开
/*eslint no-useless-computed-key: "error"*/
const a = { 'a': 0 };
const b = { 0: 0 };
const c = { x() {} };
const d = { a: 0 };
const e = { '0+1,234': 0 };
const { 0: foo } = obj;
const { 'x': bar } = obj;
class Foo {
"foo" = "bar";
0() {}
'a'() {}
get 'b'() {}
set 'c'(value) {}
static "foo" = "bar";
static 'a'() {}
}
此规则的额外正确代码示例
在 Playground 中打开
/*eslint no-useless-computed-key: "error"*/
const c = {
"__proto__": foo, // defines object's prototype
["__proto__"]: bar // defines a property named "__proto__"
};
class Foo {
["constructor"]; // instance field named "constructor"
"constructor"() {} // the constructor of this class
["constructor"]() {} // method named "constructor"
static ["constructor"]; // static field named "constructor"
static ["prototype"]; // runtime error, it would be a parsing error without `[]`
}
选项
此规则有一个对象选项
enforceForClassMembers
设置为false
将禁用类成员的此规则(默认为true
)。
enforceForClassMembers
默认情况下,此规则还会检查类声明和类表达式,因为 enforceForClassMembers
的默认值为 true
。
当 enforceForClassMembers
设置为 false
时,该规则将允许在类字段、类方法、类 getter 和类 setter 中使用不必要的计算键。
使用 { "enforceForClassMembers": false }
选项时,此规则的错误代码示例
在 Playground 中打开
/*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": false }]*/
const obj = {
,
,
,
,
};
使用 { "enforceForClassMembers": false }
选项时,此规则的正确代码示例
在 Playground 中打开
/*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": false }]*/
class SomeClass {
["foo"] = "bar";
[42] = "baz";
['a']() {}
get ['b']() {}
set ['c'](value) {}
static ["foo"] = "bar";
static ['baz']() {}
}
何时不使用
如果您不想收到关于不必要的计算属性键的通知,您可以安全地禁用此规则。
版本
此规则在 ESLint v2.9.0 中引入。