ban-ts-comment
禁止使用
@ts-<命令>
註解或要求在命令後附上說明。
延伸 "plugin:@typescript-eslint/recommended"
in an ESLint configuration enables this rule.
此規則所回報的某些問題可由編輯器中的手動修正進行修復 建議.
TypeScript 提供了幾個指令註解,可用於變更它處理檔案的方式。使用這些來隱藏 TypeScript 編譯器錯誤會降低 TypeScript 的整體效能。相反地,最好修正程式碼的類型,使指令變得不必要。
TypeScript 支援的指令註解為
// @ts-expect-error
// @ts-ignore
// @ts-nocheck
// @ts-check
此規則讓您可以設定您要在程式碼庫中允許哪些指令註解。
module.exports = {
"rules": {
"@typescript-eslint/ban-ts-comment": "error"
}
};
在遊戲場中嘗試此規則 ↗
選項
此規則適用下列選項,並在 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-error
、ts-ignore
、ts-nocheck
、ts-check
指令
特定指令的值為 true
表示此規則會在找到使用該指令時回報。
- ❌ 不正確
- ✅ 正確
if (false) {
// @ts-ignore: Unreachable code error
console.log('hello');
}
if (false) {
/* @ts-ignore: Unreachable code error */
console.log('hello');
}
在 Playground 中開啟if (false) {
// Compiler warns about 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 中開啟if (false) {
// @ts-expect-error: Unreachable code error
console.log('hello');
}
if (false) {
/* @ts-expect-error: Unreachable code 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 中開啟// @ts-expect-error: TS1234 because the library definition is wrong
const a = doSomething('hello');
在 Playground 中開啟minimumDescriptionLength
使用 minimumDescriptionLength
設定指令使用 allow-with-description
選項的描述長度下限。
例如,使用 { 'ts-expect-error': 'allow-with-description', minimumDescriptionLength: 10 }
結果將會是
- ❌ 不正確
- ✅ 正確
if (false) {
// @ts-expect-error: TODO
console.log('hello');
}
在 Playground 中開啟if (false) {
// @ts-expect-error The rationale for this override is described in issue #1337 on GitLab
console.log('hello');
}
在 Playground 中開啟何時不應使用
如果你的專案或其相依專案不是基於強型態安全性設計,就表示很難持續遵守適當的 TypeScript 語意。你可以考慮在這些特定情況下使用 ESLint disable 註解,而不是完全停用此規則。
延伸閱讀
- TypeScript JavaScript 檔案的型態檢查