禁止魔法數字
禁止神奇數字。
此規則擴充了基本 eslint/no-magic-numbers
規則。它加入了對下列內容的支援
- 數字文字類型(
type T = 1
), enum
成員(enum Foo { bar = 1 }
),readonly
類別屬性(class Foo { readonly bar = 1 }
)。
如何使用
.eslintrc.cjs
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"no-magic-numbers": "off",
"@typescript-eslint/no-magic-numbers": "error"
}
};
在遊樂場中嘗試此規則 ↗
選項
請見 eslint/no-magic-numbers
選項。
此規則會新增以下選項
interface Options extends BaseNoMagicNumbersOptions {
ignoreEnums?: boolean;
ignoreNumericLiteralTypes?: boolean;
ignoreReadonlyClassProperties?: boolean;
ignoreTypeIndexes?: boolean;
}
const defaultOptions: Options = {
...baseNoMagicNumbersDefaultOptions,
ignoreEnums: false,
ignoreNumericLiteralTypes: false,
ignoreReadonlyClassProperties: false,
ignoreTypeIndexes: false,
};
ignoreEnums
布林值,用於指定在 TypeScript 中使用的列舉是否被視為正確。預設為 false
。
{ "ignoreEnums": false }
選項的不正確程式碼範例
enum foo {
SECOND = 1000,
}
在遊樂場中開啟{ "ignoreEnums": true }
選項的正確程式碼範例
enum foo {
SECOND = 1000,
}
在遊樂場中開啟ignoreNumericLiteralTypes
布林值,用於指定在 TypeScript 數字文字類型中使用的數字是否被視為正確。預設為 false
。
{ "ignoreNumericLiteralTypes": false }
選項的不正確程式碼範例
type SmallPrimes = 2 | 3 | 5 | 7 | 11;
在遊樂場中開啟{ "ignoreNumericLiteralTypes": true }
選項的正確程式碼範例
type SmallPrimes = 2 | 3 | 5 | 7 | 11;
在遊樂場中開啟ignoreReadonlyClassProperties
{ "ignoreReadonlyClassProperties": false }
選項的不正確程式碼範例
class Foo {
readonly A = 1;
readonly B = 2;
public static readonly C = 1;
static readonly D = 1;
}
在遊樂場中開啟{ "ignoreReadonlyClassProperties": true }
選項的正確程式碼範例
class Foo {
readonly A = 1;
readonly B = 2;
public static readonly C = 1;
static readonly D = 1;
}
在遊樂場中開啟ignoreTypeIndexes
布林值,用於指定用於索引類型數字是否正確。預設為 false
。
{ "ignoreTypeIndexes": false }
選項的不正確程式碼範例
type Foo = Bar[0];
type Baz = Parameters<Foo>[2];
在遊樂場中開啟{ "ignoreTypeIndexes": true }
選項的正確程式碼範例
type Foo = Bar[0];
type Baz = Parameters<Foo>[2];
在遊樂場中開啟何時不使用
如果您的專案經常使用常數字,而且您不希望使用額外的空間來宣告它們,那麼此規則可能不適用於您。我們建議至少使用描述性的註解和/或名稱來描述常數。您可以考慮使用 ESLint 禁用的註解,而不是完全停用此規則。