'tslint one line rule misplaced 'else'
I have such config in tslint.json for one line rule
one-line": [true,
"check-open-brace",
"check-catch",
"check-else",
"check-whitespace"
],
When I have code lines like that:
if(SomethingTrue) { next("a"); }
else { next("b"); }
I've got warning:
(one-line) file.ts[17, 9]: misplaced 'else'
Why that is happens?
Is it bad practice to have one line else?
Solution 1:[1]
if (condition is true) {
// do something;
}
else {
// do something else;
}
Notice that else comes next to }
if (condition is true) {
// do something;
} else {
// do something else;
}
Solution 2:[2]
According to the tslint docs the problem is that when "check-else" is specified under one-line the else must be on the same line as the closing brace for your if.
So in your case instead of:
if(SomethingTrue) { next("a"); }
else { next("b"); }
Use this format:
if(SomethingTrue) { next("a"); } else { next("b"); }
Solution 3:[3]
if (condition) {
// Your Code
} else {
// Your Code
}
End of If and start of else should be on the same line.
Solution 4:[4]
Make sure your else if or else starts on the same line where you closed previous condition (}).
if (some condition) {
// logic to be executed
} else if (some additional condition) {
// logic to be executed
} else {
// logic to be executed
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeffrey Roosendaal |
| Solution 2 | zejuel |
| Solution 3 | Jeffrey Roosendaal |
| Solution 4 | Pranay Bunari |
