Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Bug: prefer-optional-chain suggests optional chaining during strict null equality check #7654

Closed
@justinbhopper

Description

@justinbhopper

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.2.2&fileType=.tsx&code=LAKAlgdgLgpgTgMwIYGMYAIAiSpPQb1HXQHoT0BJAWwAcB7OXaALnQAZ0wBndPANyQAbMABN0AwQFcYRcUOmsIkqgCN46AD7olgwQG5QAX1CgUdCFyjoROJK2y5N2ybvQBedAHMYUB0gAUAJQGIKBk6ADCABYwKADWkJ7oKnRQUehpOOgABja42Zw8UHCSaQCe6ACCAHKYGVFZubYAdBLSBdzaqc6u-mooSJJcGBydEqKBoGAI6P55eABkC9YtbRgAhG4eOoKBBLJmFnSCMM2CdJ7%2BAETVympwrFfoANQruK3yMMFG6DCCw-sQMRDlxjqdzpcrhQIOMxPNmldviBjKEQAhJBAUFAwOYvD4-EF7LYnDtAcQ4D5JHAIAQ5FIYKwAMzoQwhFGgIA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Y6RAM0WloHsalfkwCG8WmQAWo5uii9o-aJHBgAviHVA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

const data: Data | null = getData();

// Checking both that `data` is truthy AND that `data.value` is not null (because 0 is valid)
if (data && data.value !== null) {
  console.log("Number: " + data.value);
} else {
  console.log("Invalid data.");
}

ESLint Config

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

tsconfig

No response

Expected Result

I expect in this case the rule would not suggest using optional chaining, because there is no way to check that data is truthy and that value is not null in a single condition.

Actual Result

The rule suggests a fix of data?.value !== null as the condition, but this condition means we are no longer checking if data is null. Applying the fix changes the logic and causes downstream errors (see playground).

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issuebugSomething isn't workinglocked due to agePlease open a new issue if you'd like to say more. See https://typescript-eslint.io/contributing.package: 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