typescript-eslint: [no-unnecessary-condition] Many false positives with `undefined`

  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have read the FAQ and my problem is not listed.

Repro

{
  "rules": {
    "@typescript-eslint/no-unnecessary-condition": "error"
  }
}
const a = [1, 2, 3];
if (a[4] !== undefined) {
  console.log(a[4]);
}

Expected Result

No errors.

Actual Result

It says a[4] !== undefined is an unnecessary condition.

Additional Info

This is because Typescript’s type signatures for array access is wrong. It should include undefined as a possible return value but it does not.

Until they fix that, can I suggest that an option is added to this rule to ignore unnecessary conditions involving undefined?

Versions

All latest.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 15 (7 by maintainers)

Commits related to this issue

Most upvoted comments

Actually I just saw this comment that we’ll be able to fix the array access type so it returns | undefined in Typescript 4.1. Kind of looked like it was going to take a lot longer than that to land! I think fixing the underlying issue in Typescript is a better solution than working around the current broken behaviour in ESLint so I will just wait for that and close this.

consistent-type-imports is the only rule we have in our package which leverage scope analysis.

You can also review the eslint core codebase, just search the codebase for context.getScope

Note that there is an open PR to TypeScript implementing an option adding undefined to index signatures: https://github.com/microsoft/TypeScript/pull/39560