prefer-ts-expect-error
強制使用
@ts-expect-error
而不是@ts-ignore
。
此規則報告的一些問題可透過 --fix
ESLint 指令列選項自動修正.
此規則已棄用,建議採用 @typescript-eslint/ban-ts-comment
。此規則 (@typescript-eslint/prefer-ts-expect-error
) 會在未來主要版本的 typescript-eslint 中移除。
在首次建立時,@typescript-eslint/ban-ts-comment
規則只負責建議移除 @ts-ignore
指示。它後來已更新為建議以 @ts-expect-error
指示取代 @ts-ignore
,因此它完全取代 @typescript-eslint/prefer-ts-expect-error
。
TypeScript 允許你在開始於 @ts-ignore
或 @ts-expect-error
的註解後立刻放置於有錯誤的行之前,從而壓制該行中的所有錯誤。兩個指令運作方式相同,除了 @ts-expect-error
會在原本沒有錯誤的行的前端產生類型錯誤。
這表示很容易忘記 @ts-ignore
,並在已壓制的錯誤修正後仍置於程式碼中。這十分危險,因為若在該行出現新錯誤時,將會被已遺忘的 @ts-ignore
壓制,從而被忽略。
module.exports = {
"rules": {
"@typescript-eslint/prefer-ts-expect-error": "error"
}
};
在展示場中嘗試此規則 ↗
範例
此規則會回報任何使用 @ts-ignore
的情況,包括以 @ts-expect-error
取代的修正程式。
- ❌ 錯誤
- ✅ 正確
// @ts-ignore
const str: string = 1;
/**
* Explaining comment
*
* @ts-ignore */
const multiLine: number = 'value';
/** @ts-ignore */
const block: string = 1;
const isOptionEnabled = (key: string): boolean => {
// @ts-ignore: if key isn't in globalOptions it'll be undefined which is false
return !!globalOptions[key];
};
在展示場中開啟// @ts-expect-error
const str: string = 1;
/**
* Explaining comment
*
* @ts-expect-error */
const multiLine: number = 'value';
/** @ts-expect-error */
const block: string = 1;
const isOptionEnabled = (key: string): boolean => {
// @ts-expect-error: if key isn't in globalOptions it'll be undefined which is false
return !!globalOptions[key];
};
在展示場中開啟選項
此規則不可設定。
不應使用的時機
如果您編譯多個 TypeScript 版本而且使用 @ts-ignore
來忽略特定版本類型錯誤,此規則可能會礙事。您可以考慮在那些特定情況中使用 ESLint disable 註解,而不是完全停用此規則。