no-useless-computed-key
禁止在物件和類別中使用不必要的計算屬性鍵
使用字面值(例如)的計算屬性是不必要的
const foo = {["a"]: "b"};
程式碼可以改寫為
const foo = {"a": "b"};
規則細節
此規則禁止不必要地使用計算屬性鍵。
此規則的錯誤程式碼範例
在線上實驗場中開啟
/*eslint no-useless-computed-key: "error"*/
const a = { };
const b = { };
const c = { };
const d = { };
const e = { };
const { } = obj;
const { } = obj;
class Foo {
}
此規則的正確程式碼範例
在線上實驗場中開啟
/*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'() {}
}
此規則的其他正確程式碼範例
在線上實驗場中開啟
/*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 }
選項時,此規則的錯誤程式碼範例
在線上實驗場中開啟
/*eslint no-useless-computed-key: ["error", { "enforceForClassMembers": false }]*/
const obj = {
,
,
,
,
};
使用 { "enforceForClassMembers": false }
選項時,此規則的正確程式碼範例
在線上實驗場中開啟
/*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 中引入。