eslint/no-else-return 細心な注意
何をするか
if 文の中で return 文の後に else ブロックを使用することを禁止します
なぜこれは悪いのか?
if ブロックに return 文が含まれている場合、その後の else ブロックは不要です。その中身はブロックの外に移動できます。
javascript
function foo() {
if (x) {
return y;
} else {
return z;
}
}このルールは、return 文を含む if 文の後に不必要なブロックがあることを強調するために設計されています。そのため、すべての return 文を含む連続した if チェーンの後に else が続く場合、警告が出ます。
例
allowElseIf: true
このルールに対する誤りの例:
javascript
function foo1() {
if (x) {
return y;
} else {
return z;
}
}
function foo2() {
if (x) {
return y;
} else if (z) {
return w;
} else {
return t;
}
}
function foo3() {
if (x) {
return y;
} else {
var t = "foo";
}
return t;
}
function foo4() {
if (error) {
return "It failed";
} else {
if (loading) {
return "It's still loading";
}
}
}
// ネストされた出現に対して2つの警告
function foo5() {
if (x) {
if (y) {
return y;
} else {
return x;
}
} else {
return z;
}
}このルールに対する正しい例:
javascript
function foo1() {
if (x) {
return y;
}
return z;
}
function foo2() {
if (x) {
return y;
} else if (z) {
var t = "foo";
} else {
return w;
}
}
function foo3() {
if (x) {
if (z) {
return y;
}
} else {
return z;
}
}
function foo4() {
if (error) {
return "It failed";
} else if (loading) {
return "It's still loading";
}
}設定
このルールは以下のプロパティを持つ設定オブジェクトを受け入れます:
allowElseIf
type: boolean
default: true
return 文の後に else if ブロックを使用することを許可するかどうか。
allowElseIf: false の場合のこのルールに対する誤りの例:
javascript
function foo() {
if (error) {
return "It failed";
} else if (loading) {
return "It's still loading";
}
}allowElseIf: false の場合のこのルールに対する正しい例:
javascript
function foo() {
if (error) {
return "It failed";
}
if (loading) {
return "It's still loading";
}
}使用方法
このルールを設定ファイルまたは CLI で有効化するには、次のように使用できます:
json
{
"rules": {
"no-else-return": "error"
}
}bash
oxlint --deny no-else-return