eslint/no-magic-numbers 風格
此規則的作用
no-magic-numbers 規則旨在通過確保特殊數字被聲明為常數,以使其含義明確,從而使程式碼更具可讀性並更容易重構。目前的實作不支援陣列索引內的 BigInt 數字。
為什麼這是不好的?
「魔術數字」是指在程式碼中多次出現但沒有明確含義的數字。它們最好用具名的常數取代。
範例
此規則的不正確程式碼範例
javascript
var dutyFreePrice = 100;
var finalPrice = dutyFreePrice + dutyFreePrice * 0.25;
此規則在 "ignore" 選項下的正確程式碼範例
javascript
/*typescript no-magic-numbers: ["error", { "ignore": [1] }]*/
var data = ["foo", "bar", "baz"];
var dataLast = data.length && data[data.length - 1];
此規則在 "ignoreArrayIndexes" 選項下的正確程式碼範例
javascript
/*typescript no-magic-numbers: ["error", { "ignoreArrayIndexes": true }]*/
var item = data[2];
data[100] = a;
f(data[0]);
a = data[-0]; // same as data[0], -0 will be coerced to "0"
a = data[0xab];
a = data[5.6e1];
a = data[4294967294]; // max array index
此規則在 "ignoreDefaultValues" 選項下的正確程式碼範例
javascript
/*typescript no-magic-numbers: ["error", { "ignoreDefaultValues": true }]*/
const { tax = 0.25 } = accountancy;
function mapParallel(concurrency = 3) {
/***/
}
此規則在 "ignoreClassFieldInitialValues" 選項下的正確程式碼範例
javascript
/*typescript no-magic-numbers: ["error", { "ignoreClassFieldInitialValues": true }]*/
class C {
foo = 2;
bar = -3;
#baz = 4;
static qux = 5;
}
此規則在 "enforceConst" 選項下的不正確程式碼範例
javascript
/*typescript no-magic-numbers: ["error", { "enforceConst": true }]*/
var TAX = 0.25;
此規則在 "detectObjects" 選項下的不正確程式碼範例
javascript
/*typescript no-magic-numbers: ["error", { "detectObjects": true }]*/
var magic = {
tax: 0.25,
};
此規則在 "detectObjects" 選項下的正確程式碼範例
javascript
/*typescript no-magic-numbers: ["error", { "detectObjects": true }]*/
var TAX = 0.25;
var magic = {
tax: TAX,
};
此規則在 "ignoreEnums" 選項下的正確程式碼範例
typescript
/*typescript no-magic-numbers: ["error", { "ignoreEnums": true }]*/
enum foo {
SECOND = 1000,
}
此規則在 "ignoreNumericLiteralTypes" 選項下的正確程式碼範例
typescript
/*typescript no-magic-numbers: ["error", { "ignoreNumericLiteralTypes": true }]*/
type SmallPrimes = 2 | 3 | 5 | 7 | 11;
此規則在 "ignoreReadonlyClassProperties" 選項下的正確程式碼範例
typescript
/*typescript no-magic-numbers: ["error", { "ignoreReadonlyClassProperties": true }]*/
class Foo {
readonly A = 1;
readonly B = 2;
public static readonly C = 1;
static readonly D = 1;
}
此規則在 "ignoreTypeIndexes" 選項下的正確程式碼範例
typescript
/*typescript no-magic-numbers: ["error", { "ignoreTypeIndexes": true }]*/
type Foo = Bar[0];
type Baz = Parameters<Foo>[2];