void 型式の式の混乱を避ける
void 型の式はステートメント位置に記述する必要があります。
拡張 "plugin:@typescript-eslint/"strict-type-checked"
を ESLint 設定 で有効にすると、このルールが有効になります。
このルールによって報告される問題の一部は、 --fix
ESLint コマンドラインオプション.
によって手動で修正できます。 💭 このルールを実行するには
型情報
が必要です。
module.exports = {
"rules": {
"@typescript-eslint/no-confusing-void-expression": "error"
}
};
.eslintrc.cjs
プレイグラウンドでこのルールを試す ↗
- 例
- ❌ 間違い
// 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 フォーマッターを使用する場合、そのようなコードは 1 行ではなく 3 行にわたって広がります。
promise.then(value => window.postMessage(value));
✅ 正解このオプションが有効になっている場合に追加の**正しい**コードの例
`ignoreVoidOperator`
混乱を招くが有効な void 式の使用方法を明示的にマークするために、明確な構文のみを使用することが望ましい場合があります。このオプションは、`void` 演算子で明示的にラップされた void 式を許可します。これは、他の開発者がこのコードスタイルを認識している限り、混乱を避けるのに役立ちます。
すべての矢印関数の省略形を中括弧で囲むのは望ましくない場合があります。特に、Prettier フォーマッターを使用する場合、そのようなコードは 1 行ではなく 3 行にわたって広がります。
// 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` 関連のバグの恐れよりも簡潔なコーディングスタイルを強く好む場合も、このルールを避けることができます。
型チェックされた lint ルールは、従来の lint ルールよりも強力ですが、型チェックされた linting を設定する必要があります。型チェックされたルールを有効にした後にパフォーマンスの低下が発生した場合は、パフォーマンスのトラブルシューティング を参照してください。