Rule change proposal regarding `prefer-ternary`
See original GitHub issueTernaries are a useful syntactic construct for const
assignments. They reduce a let/if/else mess to (hopefully) a single line. They can also be misused in various ways. The current implementation of the rule always enforces the use of a ternary if both branches of an if/else expression return the same type. This is unfortunately coincidentally true for Promises and Errors. Take these two examples:
if (condition) {
await doSomething();
} else {
await doSomeOtherThing();
}
The rule corrects this to:
await (condition ? doSomething() : doSomeOtherThing());
if (condition) {
throw new ThisKindOfError();
} else {
throw new ThatKindOfError();
}
The rule corrects this to:
throw (condition ? new ThisKindOfError() : new ThatKindOfError());
Both cases I would categorize as misuse of ternaries, since they do nothing more than deduplicate a await
/throw
and make the code less readable.
However, I would still like the rule to catch valid cases, which mostly come in this form:
let someVariable;
if (condition) {
someVariable = thisValue;
} else {
someVariable = otherValue;
}
This is (correctly) corrected to:
const someVariable = condition ? thisValue : otherValue;
I propose that the rule should be configurable to only apply to assignments. This would exclude situations using await/throw/yield.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:8
- Comments:7 (3 by maintainers)
Top GitHub Comments
Regarding
I agree that it is better than what the rule suggests, but it is still much worse than
since it conceals the potential side-effects of those asynchronous operations.
I am for the suggested more options, since in our case we prefer assignments and returns to be checked. If there are no other voices on this, a single option that only checks assignments and returns would be fine in my opinion. But I can see that others might only want assignments or even only returns.
Yeah, I agree. It seemed nice at first but having used it in practice, I agree, an if-statement would be better here.