Skip to content

Bug: [prefer-optional-chain] unsafe fix when the chain ends with a null comparison (a.b === null) #11840

@mdm317

Description

@mdm317

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.9.3&fileType=.tsx&code=CYUwxgNghgTiAEYD2A7AzgF3gMyUgXPAN7wBGshKArgLakgzwA%2B81EE8Avs-FSqNgCWKEMADcAKEHZ4AClxJ4AXhW9%2BIISODMWCgHTlGKpayrsAlMXgB6a-DRUA5o5CY08DIoUB%2BA7GWqbBAANPAA7gAWgmAR8ILuKEhYIACOVIIAblAQICgYehLcIBBoCEQS8Dh4fjB6ngCiAB4ADqi5GILZsuZiNnZQ2BgM8FBgYCDNHSiOOIKNoRhR7mAwUGgRrnEyAAYK23Hu23wCwqLbBZwSEkA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Y6RAM0WloHsalfkwCG8WmQAWo5uii9o-aJHBgAviBDqgA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

declare const foo: { bar: number | null } | undefined;
if (foo === undefined || foo.bar === null) { // suggests to foo?.bar === null, which is not equivalent.
} else {
  foo.bar.toExponential(); // after accepting fix, this crashes if `foo` is `undefined`.
}

ESLint Config

{
  "rules": {
    "@typescript-eslint/prefer-optional-chain": "error"
  }

}

tsconfig

{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

Expected Result

no suggest

Actual Result

suggest to fix

Additional Info

Originally posted by @kirkwaiblinger in #11702 (comment)

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

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions