Skip to content

Bug: [prefer-optional-chain] invalid fix with array access by index #11917

Description

@Hypnosphi

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=JYOwLgpgTgZghgYwgAgGIHt3IN4FgBQyyARnFAFzIgCuAtsdANwEC%2BBBM1ICYw6IyWnFAAKGJkoYsAHyrUANvIA0ycegDOkzAG0AugEpKxTPIhwBeQsmAxkYzMgBkj1ZgB0pKMgC8v1xu0ABl0Afg8yfRwCIiIoCDBqKAEwKGoIaOQ2KziEpNU4eXV0-BYgA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Y6RAM0WloHsalfkwCG8WmQAWo5uii9o-aJHBgAviHVA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eFYDArugDTg10NM8AOXapUAYQAW6aAGsylDul4BfECqA&tokens=false

Repro Code

interface Foo {
  bar: number;
}

function main(foo: Foo | null, foos: Foo[]): boolean {
  if (foo && foo.bar === foos[0]?.bar) {
    return true
  }
  return false
}

ESLint Config

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

tsconfig

{
  "compilerOptions": {
    "strict": true,
    "strictNullChecks": true
  }
}

Expected Result

No error or autofix

Actual Result

Autofix provides an invalid result:

function main(foo: Foo | null, foos: Foo[]): boolean {
  if (foo?.bar === foos[0]?.bar) {
    return true
  }
  return false
}

main(null, []) was false before the fix but now it's true

Additional Info

Happens after upgrading to 8.51.0, probably introduced with #11835

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

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions