🌐 AI搜索 & 代理 主页
Skip to content

Bug: @typescript-eslint/prefer-optional-chain flags situations where an optional chain would change behavior #11700

@aboks

Description

@aboks

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=CYUwxgNghgTiAEYD2A7AzgF3lAXPA3vAEYD8emMAligObwC%2BA3AFDOUBm8AFAIRTwAfAdgB0ReAF4p8AETskSGQEoCzePGb0gA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Y6RAM0WloHsalfkwCG8WmQAWo5uigB3UdCaRwYAL4gNQA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

declare const a: { b?: string };

if (!a || a.b === "foo") {
  
}

ESLint Config

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

tsconfig

{
  "compilerOptions": {}
}

Expected Result

I expect that no error from @typescript-eslint/prefer-optional-chain is triggered on the third line, as an optional chain would change behavior.

Actual Result

An error from @typescript-eslint/prefer-optional-chain is triggered on the third line. When autofixed, this produces the code

declare const a: { b?: string };

if (a?.b === "foo") {
  
}

When a.b is undefined, the original comparison produced the value true, executing the code within the if-block. The 'autofixed' code produces false in that case, skipping the code within the if-block.

Additional Info

This seems due to the changes in #11533. The comment in #11533 (comment) already hints at this incorrect behavior.

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