Rule proposal: `prefer-logical-operator-over-ternary` for explicit truthy, falsy and nullish conditions
Samuel-Therrien-Beslogic opened this issue · comments
Samuel T. commented
Description
I'd like prefer-logical-operator-over-ternary
to catch the following cases:
Fail
// Nullish coalescing
foo == null ? bar : foo // Autofix to `foo ?? bar`
foo == undefined ? bar : foo // Autofix to `foo ?? bar`
foo == false ? bar : foo // Same suggestion as `!foo ? bar : foo`
foo == true ? foo : bar // Same suggestion as `foo ? foo : bar`
// Optional chaining
foo === undefined ? foo : foo.bar // Autofix to `foo?.bar`
foo == undefined ? undefined : foo.bar // Autofix to `foo?.bar`
foo == null ? undefined : foo.bar // Autofix to `foo?.bar`
Pass
foo == null ? foo : bar
foo == undefined ? foo : bar
foo == false ? foo : bar
foo == true ? bar : foo
foo == false ? bar : false
foo == true ? true : bar
// Technically these can change the return type from `null` to `undefined`. So I'm not sure if they should pass or fail with suggestion
foo == undefined ? foo : foo.bar // Suggests `foo?.bar`
foo == null ? foo : foo.bar // Suggests `foo?.bar`
Additional Info
https://github.com/SonarSource/eslint-plugin-sonarjs/blob/master/docs/rules/no-redundant-boolean.md catches the redundant falsy/truthy boolean conditional in a ternary. But offers no autofix.
https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v46.0.1/docs/rules/no-negated-condition.md already takes cares of the !=
cases to I didn't list them here.
ts(5076)
prevents mixing &&
/||
with ??
without parenthesis. So some autofix might require adding parenthesis.
Federico Brigante commented