no-confusing-void-expression
需要出現型別為 void 的運算式在陳述句位置。
擴展中 "plugin:@typescript-eslint/strict-type-checked"
在 ESLint 組態 啟用此規則。
此規則回報的一些問題可透過 --fix
ESLint 命令列選項自動修正.
此規則回報的一些問題可透過編輯器手動修正 建議事項.
此規則需要 型別資訊 才能執行。
TypeScript 中的 void
指的是一個表示為應該被忽略的函式回傳值。嘗試使用 void
型別的值(例如,儲存已呼叫函式的結果到變數中),通常表示一個程式設計人員錯誤。即使在正確使用下,void
也可能讓其他開發人員感到混淆。
此規則可防止 void
型別運算式用在特定位置(例如,指派給變數、提供為函式引數或從函式回傳),以免引起誤解。
module.exports = {
"rules": {
"@typescript-eslint/no-confusing-void-expression": "error"
}
};
在試驗場中嘗試此規則 ↗
範例
- ❌ 錯誤
- ✅ 正確
// somebody forgot that `alert` doesn't return anything
const response = alert('Are you sure?');
console.log(alert('Are you sure?'));
// it's not obvious whether the chained promise will contain the response (fixable)
promise.then(value => window.postMessage(value));
// it looks like we are returning the result of `console.error` (fixable)
function doSomething() {
if (!somethingToDo) {
return console.error('Nothing to do!');
}
console.log('Doing a thing...');
}
在遊樂場中開啟// just a regular void function in a statement position
alert('Hello, world!');
// this function returns a boolean value so it's ok
const response = confirm('Are you sure?');
console.log(confirm('Are you sure?'));
// now it's obvious that `postMessage` doesn't return any response
promise.then(value => {
window.postMessage(value);
});
// now it's explicit that we want to log the error and return early
function doSomething() {
if (!somethingToDo) {
console.error('Nothing to do!');
return;
}
console.log('Doing a thing...');
}
// using logical expressions for their side effects is fine
cond && console.log('true');
cond || console.error('false');
cond ? console.log('true') : console.error('false');
在遊樂場中開啟選項
此規則接受下列選項
type Options = [
{
ignoreArrowShorthand?: boolean;
ignoreVoidOperator?: boolean;
},
];
const defaultOptions: Options = [
{ ignoreArrowShorthand: false, ignoreVoidOperator: false },
];
ignoreArrowShorthand
不希望每個箭頭函式簡寫運算式都加上大括號。尤其是當使用 Prettier 格式化程式時,因為它會把這樣的程式碼分配到三行而不是一行。
啟用此選項時,以下是額外正確程式碼範例
promise.then(value => window.postMessage(value));
在遊樂場中開啟ignoreVoidOperator
僅針對某些不同的語法標明令人困惑但有效的 void 運算式用途可能是比較好的。此選項允許明確包覆在 void
運算式中的 void 運算式。只要其他開發人員已得知此程式碼樣式,這樣有助於他們避免產生混淆。
此選項也變更常用案例中的自動修正程式碼,以使用 void
運算式。它也會啟用建議修正程式碼,以將 void 運算式包覆在 void
運算式中,以針對報告的每個問題進行修正。
啟用此選項時,以下是額外正確程式碼範例
// now it's obvious that we don't expect any response
promise.then(value => void window.postMessage(value));
// now it's explicit that we don't want to return anything
function doSomething() {
if (!somethingToDo) {
return void console.error('Nothing to do!');
}
console.log('Doing a thing...');
}
// we are sure that we want to always log `undefined`
console.log(void alert('Hello, world!'));
在遊樂場中開啟何時不使用
前往其定義或在 IDE 中將指標懸停在函式上,就能檢查函式的傳回類型。如果您不重視明確指出實際程式碼中的 void 型別,就不要使用這條規則。此外,如果您強烈偏好簡潔的編碼樣式,且勝於害怕發生與 void
相關的錯誤,則可以略過這條規則。
類型檢查的程式碼檢查規則比傳統的程式碼檢查規則更為強大,但需要設定 類型檢查的程式碼檢查。如果你在啟用類型檢查規則後,效能有下降的情形,請參閱 效能疑難排解。