sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rule proposal: `prefer-logical-operator-over-ternary` for explicit truthy, falsy and nullish conditions

Samuel-Therrien-Beslogic opened this issue · comments

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.

Correct me if I'm wrong, but I see some or full overlap with:

@fregante The optional chaining part for sure. I'm not sure if nullish coalescence as I've presented it is included by the other proposals. But if they are both implemented and I feel something is still missing, then I'll reopen.