typescript - tslint misplaced 'else' (one-line)
Asked Answered
M

2

9

I'm using TSLint extension for VS Code. I got bunch of [tslint] misplaced 'else' (one-line) warnings. For example, at the below code sample, linter underlines else word and gives same warning:

Code:

if (user.isAdmin) {
    this.uiRouter.stateService.go('app.admin');
}
else {
    this.sharedVariables.user = user;
    this.navigateByUserType(user);
}

What is the problem with this code?

Mozzarella answered 17/3, 2017 at 6:33 Comment(5)
The error message says exactly what the problem is. What's so hard tio understand about that?Divalent
Google "[tslint] misplaced 'else' (one-line)". One answer will be from the doc page which says in the first line Requires the specified tokens to be on the same line as the expression preceding them. The first result will be this SO question which also gives a clear answer.Divalent
brother @torazaburo it's not always that easy. On line also means all conditional based code in single line.Anderegg
I did that and this is the top hit.Kariekaril
The answer is there's nothing wrong with it, this is excellent formatting. However to make lint stop complaining, get curly braces on the left and right side of else.Grassplot
G
45

From the tslint one-line rule documentation

Rule: one-line

Requires the specified tokens to be on the same line as the expression preceding them.

You have a tslint rule enabled called one-line with a token specified called check-else. This tells tslint to warn for every else statement that isn't on the same line as the previous ending curly brace. If you move up the else statement to the same line as the ending curly brace of the if statement the tslint rule should be satisfied.

if (user.isAdmin) {
    this.uiRouter.stateService.go('app.admin');
} else {
    this.sharedVariables.user = user;
    this.navigateByUserType(user);
}
Gilstrap answered 18/3, 2017 at 10:43 Comment(0)
W
-1

Always ensure to have the ending if curly bracket and the else statement on the same line.

This is as per TSLint one-line rule documentation.

Workday answered 6/1, 2021 at 8:42 Comment(2)
How is this answer better than the accepted one? It's basically the same without the references and explanation.Iz
Sometimes people just want a straight to the point answer. And was basically using my experience in resolving this issue. I should have read the other responses before providing mine.Workday

© 2022 - 2024 — McMap. All rights reserved.