Skip to content

Bug: [prefer-optional-chain] Unsoundly fixes a !== undefined && a.b !== null to a?.b !== null #10484

@andersk

Description

@andersk

Before You File a Bug Report Please Confirm You Have Done The Following...

  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have searched for related issues and found none that matched my issue.
  • I have read the FAQ and my problem is not listed.

Playground Link

https://typescript-eslint.io/play/#ts=5.6.3&fileType=.tsx&code=GYVwdgxgLglg9mABMAFAQwPwC5EG9EBGOAzlAE4xgDmiAPomCADZOIC%2BAlDgG5wwAmeAFCJEMYInSIAhAF5ZicPwCmwSssEAyTYjQA6AjPkNmTDsNGiICYnCbK9TOFXQGOI9kLZCgA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Y6RAM0WloHsalfkwCG8WmQAWo5uii9o-aJHBgAviHVA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eFYDAruuGAL4g9A&tokens=false

Repro Code

function f(a?: { b: string | null }): void {
  if (a !== undefined && a.b !== null) {
    console.log(a.b)
  }
}

ESLint Config

module.exports = {
  "rules": {
    "@typescript-eslint/prefer-optional-chain": "error"
  }
}

tsconfig

{
  "compilerOptions": {
    "strict": true
  }
}

Expected Result

No fix.

Actual Result

prefer-optional-chain produces this fix:

 function f(a?: { b: string | null }): void {
-  if (a !== undefined && a.b !== null) {
+  if (a?.b !== null) {
     console.log(a.b)
   }
 }

This is unsound because if a is undefined, then a?.b is undefined, not null.

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issuebugSomething isn't workingpackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions