Skip to content
← Back to rules

eslint/no-useless-computed-key スタイル

An auto-fix is available for this rule.

何をするか

オブジェクトおよびクラス内の不要な計算プロパティキーの使用を禁止します

なぜ問題なのか

次のようなリテラルを使用して計算プロパティを使用するのは不必要です:

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

このコードは次のように書き直すことができます:

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

このルールに違反する誤ったコードの例:

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

class Foo {
  ["foo"] = "bar";
  [0]() {}
  static ["foo"] = "bar";
  get ["b"]() {}
  set ["c"](value) {}
}

このルールに従う正しいコードの例:

js
const a = { a: 0 };
const b = { 0: 0 };
const c = { x() {} };
const e = { "0+1,234": 0 };

class Foo {
  foo = "bar";
  0() {}
  a() {}
  static foo = "bar";
}

このルールに従う追加の正しいコードの例:

js
const c = {
  __proto__: foo, // オブジェクトのプロトタイプを定義
  ["__proto__"]: bar, // 名前が "__proto__" のプロパティを定義
};
class Foo {
  ["constructor"]; // "constructor" という名前のインスタンスフィールド
  constructor() {} // そのクラスのコンストラクタ
  static ["constructor"]; // "constructor" という名前の静的フィールド
  static ["prototype"]; // 実行時エラー。`[]` がないと構文エラーになる
}

設定

このルールは以下のプロパティを持つ設定オブジェクトを受け入れます。

enforceForClassMembers

型: boolean

デフォルト: true

enforceForClassMembers オプションは、このルールがクラスメンバ(メソッドおよびプロパティ)にも適用されるかどうかを制御します。

{ "enforceForClassMembers": false } オプションを使用した場合の正しいコードの例:

js
class SomeClass {
  ["foo"] = "bar";
  [42] = "baz";
  get ["b"]() {}
  set ["c"](value) {}
  static ["foo"] = "bar";
}

使用方法

設定ファイルまたは CLI でこのルールを有効化するには、次のように使用できます:

json
{
  "rules": {
    "no-useless-computed-key": "error"
  }
}
bash
oxlint --deny no-useless-computed-key

参照