Skip to content

useCollapsedElseIf

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"style": {
"useCollapsedElseIf": "error"
}
}
}
}

¥Description

强制使用 else if 而不是嵌套在 else 子句中的 if。

¥Enforce using else if instead of nested if in else clauses.

如果 if 语句是 else 块中的唯一语句,则使用 else if 形式通常更清楚。

¥If an if statement is the only statement in the else block, it is often clearer to use an else if form.

¥Examples

¥Invalid

if (condition) {
// ...
} else {
if (anotherCondition) {
// ...
}
}
code-block.js:3:9 lint/style/useCollapsedElseIf  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ This if statement can be collapsed into an else if statement.

1 │ if (condition) {
2 │ // …
> 3 │ } else {
│
> 4 │ if (anotherCondition) {
> 5 │ // …
> 6 │ }
│ ^
7 │ }
8 │

ℹ Safe fix: Use collapsed else if instead.

1 1 │ if (condition) {
2 2 │ // …
3 │ - }·else·{
4 │ - ····if·(anotherCondition)·{
3 │ + }·else·if·(anotherCondition)·{
5 4 │ // …
6 │ - ····}
7 │ - }
5 │ + ····}
8 6 │

if (condition) {
// ...
} else {
if (anotherCondition) {
// ...
} else {
// ...
}
}
code-block.js:3:9 lint/style/useCollapsedElseIf  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ This if statement can be collapsed into an else if statement.

1 │ if (condition) {
2 │ // …
> 3 │ } else {
│
> 4 │ if (anotherCondition) {
> 5 │ // …
> 6 │ } else {
> 7 │ // …
> 8 │ }
│ ^
9 │ }
10 │

ℹ Safe fix: Use collapsed else if instead.

1 1 │ if (condition) {
2 2 │ // …
3 │ - }·else·{
4 │ - ····if·(anotherCondition)·{
3 │ + }·else·if·(anotherCondition)·{
5 4 │ // …
6 5 │ } else {
7 6 │ // …
8 │ - ····}
9 │ - }
7 │ + ····}
10 8 │

if (condition) {
// ...
} else {
// Comment
if (anotherCondition) {
// ...
}
}
code-block.js:3:9 lint/style/useCollapsedElseIf ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ This if statement can be collapsed into an else if statement.

1 │ if (condition) {
2 │ // …
> 3 │ } else {
│
> 4 │ // Comment
> 5 │ if (anotherCondition) {
> 6 │ // …
> 7 │ }
│ ^
8 │ }
9 │

¥Valid

if (condition) {
// ...
} else if (anotherCondition) {
// ...
}
if (condition) {
// ...
} else if (anotherCondition) {
// ...
} else {
// ...
}
if (condition) {
// ...
} else {
if (anotherCondition) {
// ...
}
doSomething();
}

¥Related links