no-magic-numbers
マジックナンバーを禁止します。
このルールは、ベースとなるeslint/no-magic-numbers
ルールを拡張したものです。以下のサポートが追加されています。
- 数値リテラル型 (
type T = 1
)、 enum
メンバー (enum Foo { bar = 1 }
)、readonly
クラスプロパティ (class Foo { readonly bar = 1 }
)。
使用方法
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"
}
};
Playgroundでこのルールを試す ↗
オプション
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で使用されるenumを許可するかどうかを指定するブール値。デフォルトはfalse
です。
{ "ignoreEnums": false }
オプションでの誤ったコードの例
enum foo {
SECOND = 1000,
}
Playgroundで開く{ "ignoreEnums": true }
オプションでの正しいコードの例
enum foo {
SECOND = 1000,
}
Playgroundで開くignoreNumericLiteralTypes
TypeScriptの数値リテラル型で使用される数値を許可するかどうかを指定するブール値。デフォルトはfalse
です。
{ "ignoreNumericLiteralTypes": false }
オプションでの誤ったコードの例
type SmallPrimes = 2 | 3 | 5 | 7 | 11;
Playgroundで開く{ "ignoreNumericLiteralTypes": true }
オプションでの正しいコードの例
type SmallPrimes = 2 | 3 | 5 | 7 | 11;
Playgroundで開くignoreReadonlyClassProperties
{ "ignoreReadonlyClassProperties": false }
オプションでの誤ったコードの例
class Foo {
readonly A = 1;
readonly B = 2;
public static readonly C = 1;
static readonly D = 1;
}
Playgroundで開く{ "ignoreReadonlyClassProperties": true }
オプションでの正しいコードの例
class Foo {
readonly A = 1;
readonly B = 2;
public static readonly C = 1;
static readonly D = 1;
}
Playgroundで開くignoreTypeIndexes
型のインデックスに使用される数値を許可するかどうかを指定するブール値。デフォルトはfalse
です。
{ "ignoreTypeIndexes": false }
オプションでの誤ったコードの例
type Foo = Bar[0];
type Baz = Parameters<Foo>[2];
Playgroundで開く{ "ignoreTypeIndexes": true }
オプションでの正しいコードの例
type Foo = Bar[0];
type Baz = Parameters<Foo>[2];
Playgroundで開く使用しない場面
プロジェクトで定数を頻繁に扱い、それらを宣言する余分なスペースを取りたくない場合、このルールは向いていないかもしれません。少なくとも、定数を説明する記述的なコメントや名前を使用することを推奨します。ESLintのdisableコメントを、このルールを完全に無効にする代わりに使用することを検討してください。