Skip to content

[prefer-nullish-coalescing] eslint --fix changes behavior when Logical OR's left side is optional and can be falsy #1294

Closed
@berlysia

Description

@berlysia

Repro

{
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
      "project": "./tsconfig.json"
    },
    "plugins": [
      "@typescript-eslint"
    ],
    "rules": {
      "@typescript-eslint/prefer-nullish-coalescing": "error"
    }
  }
import assert from 'assert';

function f(arg: null | boolean): null | boolean {
  return arg;
}
function g(arg: boolean): boolean {
  return arg;
}

function h(a: null | boolean, b: boolean) {
  return f(a) || g(b);
}

assert.equal(h(true, true), true);
assert.equal(h(true, false), true);
assert.equal(h(false, true), true); // broken after fix
assert.equal(h(false, false), false); // not broken, but returns `f`'s result(bad sample...)
assert.equal(h(null, true), true);
assert.equal(h(null, false), false);

Expected Result
no report. Fallback to g() when f() is falsy.

Actual Result
@typescript-eslint/prefer-nullish-coalescing reports the error, and also the fixed output is broken.

Sample repo to reproduce the behavior: https://github.com/berlysia/typescript-eslint-nullish-coalescing-false-positive

Additional Info

This issue applies not only to boolean but also to number and string.

Versions

package version
@typescript-eslint/eslint-plugin 2.9.0
@typescript-eslint/parser 2.9.0
TypeScript 3.7.2
ESLint 6.7.2
node 12.4.0
npm 6.9.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    package: eslint-pluginIssues related to @typescript-eslint/eslint-plugintriageWaiting for team members to take a look

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions