tslint one line rule misplaced 'else'
Asked Answered
I

5

12

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?

Improper answered 8/2, 2016 at 1:32 Comment(0)
B
10

You have :

else { next("b"); }

Else must be one one line. So:

else { 
    next("b"); 
}

Is it bad practice to have one line else?

Just easier to read. Its a styleguide for consistency.

Bradberry answered 8/2, 2016 at 1:36 Comment(3)
Yes I just realized that "check-else" rule is responsible for checking that.Improper
then it is gonna be 1 line if and multiple line else which is a bit wired I thinkImproper
add check-if as well.Bradberry
G
23
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;
}
Gehlenite answered 6/4, 2017 at 1:22 Comment(0)
B
10

You have :

else { next("b"); }

Else must be one one line. So:

else { 
    next("b"); 
}

Is it bad practice to have one line else?

Just easier to read. Its a styleguide for consistency.

Bradberry answered 8/2, 2016 at 1:36 Comment(3)
Yes I just realized that "check-else" rule is responsible for checking that.Improper
then it is gonna be 1 line if and multiple line else which is a bit wired I thinkImproper
add check-if as well.Bradberry
C
4

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"); }
Cachepot answered 1/12, 2016 at 14:21 Comment(1)
Thanks for hinting to the rule responsible :)Larimor
H
3
if (condition) {
  // Your Code
} else {
  // Your Code
}

End of If and start of else should be on the same line.

Housebound answered 13/12, 2017 at 15:33 Comment(0)
D
0

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
    }
Dietetics answered 17/5, 2022 at 19:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.