版本

no-useless-computed-key

禁止在对象和类中使用不必要的计算属性键

🔧 可修复

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

❄️ 冻结

此规则目前处于冻结状态,不接受功能请求。

对于诸如以下的字面量使用计算属性是不必要的

const foo = {["a"]: "b"};

代码可以重写为

const foo = {"a": "b"};

规则详情

此规则禁止不必要地使用计算属性键。

此规则的错误代码示例

在 Playground 中打开
/*eslint no-useless-computed-key: "error"*/

const a = { ['0']: 0 };
const b = { ['0+1,234']: 0 };
const c = { [0]: 0 };
const d = { ['x']: 0 };
const e = { ['x']() {} };

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 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 = {
    ["foo"]: "bar",
    [42]: "baz",

    ['a']() {},
    get ['b']() {},
    set ['c'](value) {}
};

使用 { "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 中引入。

资源

更改语言