メインコンテンツにスキップ

ban-ts-comment

@ts-<directive> コメントを禁止するか、ディレクティブの後に説明を要求します。

拡張 "plugin:@typescript-eslint/recommended" ESLint 設定 で有効にすると、このルールが有効になります。

💡

このルールによって報告されるいくつかの問題は、エディターの 提案.

によって手動で修正できます。TypeScript は、ファイルの処理方法を変更するために使用できるいくつかのディレクティブ コメントを提供します。これらを使用して TypeScript コンパイラーのエラーを抑制すると、TypeScript 全体の有効性が低下します。代わりに、一般的にコードの型を修正して、ディレクティブを不要にすることをお勧めします。

TypeScript でサポートされているディレクティブ コメントは次のとおりです。

// @ts-expect-error
// @ts-ignore
// @ts-nocheck
// @ts-check

このルールを使用すると、コードベースで許可するディレクティブ コメントを設定できます。

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/ban-ts-comment": "error"
}
};

Playground でこのルールを試す ↗

オプション

このルールは次のオプションを受け入れ、strict 設定ではより厳格な設定が適用されます。

type DirectiveConfigSchema =
| 'allow-with-description'
| {
descriptionFormat?: string;
}
| boolean;

type Options = [
{
'ts-check'?: DirectiveConfigSchema;
'ts-expect-error'?: DirectiveConfigSchema;
'ts-ignore'?: DirectiveConfigSchema;
'ts-nocheck'?: DirectiveConfigSchema;
minimumDescriptionLength?: number;
},
];

const defaultOptionsRecommended: Options = [
{
'ts-expect-error': 'allow-with-description',
'ts-ignore': true,
'ts-nocheck': true,
'ts-check': false,
minimumDescriptionLength: 3,
},
];

// These options are merged on top of the recommended defaults
const defaultOptionsStrict: Options = [{ minimumDescriptionLength: 10 }];

デフォルトでは、エラーを抑制するのではなく有効にするため、@ts-check のみが許可されます。

ts-expect-errorts-ignorets-nocheckts-check ディレクティブ

特定のディレクティブの値が true の場合、このルールは、そのディレクティブの使用箇所を見つけると報告します。

if (false) {
// @ts-ignore: Unreachable code error
console.log('hello');
}
if (false) {
/* @ts-ignore: Unreachable code error */
console.log('hello');
}
Playground で開く

allow-with-description

特定のディレクティブの値が 'allow-with-description' の場合、このルールは、ディレクティブの後に(同じ行に)説明がないディレクティブを見つけた場合に報告します。

たとえば、{ 'ts-expect-error': 'allow-with-description' } の場合

if (false) {
// @ts-expect-error
console.log('hello');
}
if (false) {
/* @ts-expect-error */
console.log('hello');
}
Playground で開く

descriptionFormat

ディレクティブ タイプごとに、正規表現形式でカスタム形式を指定できます。パターンに一致する説明のみが許可されます。

たとえば、{ 'ts-expect-error': { descriptionFormat: '^: TS\\d+ because .+$' } } の場合

// @ts-expect-error: the library definition is wrong
const a = doSomething('hello');
Playground で開く

minimumDescriptionLength

ディレクティブに allow-with-description オプションを使用する場合、minimumDescriptionLength を使用して説明の最小長を設定します。

たとえば、{ 'ts-expect-error': 'allow-with-description', minimumDescriptionLength: 10 } の場合、次のパターンが

if (false) {
// @ts-expect-error: TODO
console.log('hello');
}
Playground で開く

使用しない場合

プロジェクトやその依存関係が強力な型の安全性を考慮して設計されていない場合、常に適切な TypeScript セマンティクスに従うことが難しい場合があります。このルールを完全に無効にする代わりに、これらの特定の状況でESLint の無効化コメントを使用することを検討してください。

参考資料

リソース