ban-types
特定の型を禁止します。
拡張 "plugin:@typescript-eslint/recommended"
を ESLint設定 に追加することで、このルールが有効になります。
このルールによって報告される問題の一部は、 --fix
ESLintコマンドラインオプションによって自動的に修正できます。.
このルールによって報告される問題の一部は、エディターの 提案によって手動で修正できます。.
いくつかの組み込み型にはエイリアスがありますが、危険または有害と見なされる型もあります。一貫性と安全性を確保するために、特定の型を禁止する方が良いことがよくあります。
このルールは特定の型を禁止し、代替案を提案できます。対応するランタイムオブジェクトの使用は禁止されません。
module.exports = {
"rules": {
"@typescript-eslint/ban-types": "error"
}
};
Playgroundでこのルールを試してください ↗
例
デフォルトオプションを使用したコードの例
- ❌ 正しくない
- ✅ 正しい
// use lower-case primitives for consistency
const str: String = 'foo';
const bool: Boolean = true;
const num: Number = 1;
const symb: Symbol = Symbol('foo');
const bigInt: BigInt = 1n;
// use a proper function type
const func: Function = () => 1;
// use safer object types
const lowerObj: Object = {};
const capitalObj: Object = { a: 'string' };
const curly1: {} = 1;
const curly2: {} = { a: 'string' };
Playgroundで開く// use lower-case primitives for consistency
const str: string = 'foo';
const bool: boolean = true;
const num: number = 1;
const symb: symbol = Symbol('foo');
const bigInt: bigint = 1n;
// use a proper function type
const func: () => number = () => 1;
// use safer object types
const lowerObj: object = {};
const capitalObj: { a: string } = { a: 'string' };
const curly1: number = 1;
const curly2: Record<'a', string> = { a: 'string' };
Playgroundで開くオプション
このルールは次のオプションを受け入れます。
type BanConfig =
/** Bans a type */
| {
/** Type to autofix replace with. Note that autofixers can be applied automatically - so you need to be careful with this option. */
fixWith?: string;
/** Custom error message */
message?: string;
/** Types to suggest replacing with. */
suggest?: string[];
}
/** Bans the type with a custom message */
| string
/** Bans the type with the default message */
| null
/** Bans the type with the default message */
| true
/** Un-bans the type (useful when paired with `extendDefaults`) */
| false;
type Options = [
{
extendDefaults?: boolean;
types?: {
[k: string]: BanConfig;
};
},
];
const defaultOptions: Options = [
{
/* See below for default options */
},
];
デフォルトオプションは、「ベストプラクティス」のセットを提供し、コードベースの安全性と標準化を目的としています。
- 大文字のプリミティブ型を使用しないでください。一貫性のために小文字の型を使用する必要があります。
Function
型は、次の理由から安全性が低いため、避けてください。- 値を呼び出す際の型安全性がないため、間違った引数を渡すのが容易です。
- クラス宣言を受け入れますが、
new
キーワードなしで呼び出されるため、呼び出し時に失敗します。
Object
と{}
型は「nullishでない値」を意味するため、避けてください。- これは多くの開発者にとって混乱のポイントであり、「任意のオブジェクト型」を意味すると考えています。
- 詳しくはこのコメントを参照してください。
デフォルトオプション
const defaultTypes: Types = {
String: {
message: 'Use string instead',
fixWith: 'string',
},
Boolean: {
message: 'Use boolean instead',
fixWith: 'boolean',
},
Number: {
message: 'Use number instead',
fixWith: 'number',
},
Symbol: {
message: 'Use symbol instead',
fixWith: 'symbol',
},
BigInt: {
message: 'Use bigint instead',
fixWith: 'bigint',
},
Function: {
message: [
'The `Function` type accepts any function-like value.',
'It provides no type safety when calling the function, which can be a common source of bugs.',
'It also accepts things like class declarations, which will throw at runtime as they will not be called with `new`.',
'If you are expecting the function to accept certain arguments, you should explicitly define the function shape.',
].join('\n'),
},
// object typing
Object: {
message: [
'The `Object` type actually means "any non-nullish value", so it is marginally better than `unknown`.',
'- If you want a type meaning "any object", you probably want `object` instead.',
'- If you want a type meaning "any value", you probably want `unknown` instead.',
'- If you really want a type meaning "any non-nullish value", you probably want `NonNullable<unknown>` instead.',
].join('\n'),
suggest: ['object', 'unknown', 'NonNullable<unknown>'],
},
'{}': {
message: [
'`{}` actually means "any non-nullish value".',
'- If you want a type meaning "any object", you probably want `object` instead.',
'- If you want a type meaning "any value", you probably want `unknown` instead.',
'- If you want a type meaning "empty object", you probably want `Record<string, never>` instead.',
'- If you really want a type meaning "any non-nullish value", you probably want `NonNullable<unknown>` instead.',
].join('\n'),
suggest: [
'object',
'unknown',
'Record<string, never>',
'NonNullable<unknown>',
],
},
};
types
禁止する型のキーと、エラーメッセージの値を持つオブジェクトです。
型は、型名リテラル(Foo
)、ジェネリックパラメーターインスタンス化を含む型名(Foo<Bar>
)、空のオブジェクトリテラル({}
)、または空のタプル型([]
)のいずれかになります。
値は次のいずれかになります。
- 報告されるエラーメッセージである文字列。または
false
(extendDefaults
を使用する場合に、この型を具体的に禁止解除するために使用します)。または- 次のプロパティを持つオブジェクト
message: string
- 型が一致したときに表示するメッセージ。fixWith?: string
- 修正プログラムを実行したときに禁止された型を置き換える文字列。省略した場合は、修正が行われません。suggest?: string[]
- 禁止された型の推奨される置換のリスト。
extendDefaults
カスタムtypes
を指定する場合は、これをtrue
に設定して、デフォルトのtypes
構成を拡張できます。これは、別の型を追加するときにデフォルトをコピーする手間を省くための便利なオプションです。
これがfalse
の場合、ルールは構成で定義されている型のみを使用します。
設定例
{
"@typescript-eslint/ban-types": [
"error",
{
"types": {
// add a custom message to help explain why not to use it
"Foo": "Don't use Foo because it is unsafe",
// add a custom message, AND tell the plugin how to fix it
"OldAPI": {
"message": "Use NewAPI instead",
"fixWith": "NewAPI",
},
// un-ban a type that's banned by default
"{}": false,
},
"extendDefaults": true,
},
],
}
使用しない場合
プロジェクトがプリミティブのクラス相当物を意図的に扱うまれなプロジェクトの場合、デフォルトのban-types
オプションを有効にするのは無駄かもしれません。代わりに、このルールを完全に無効にするのではなく、特定の状況に対してESLintの無効化コメントを使用することを検討してください。