Skip to content

[prefer-optional-chain] Ignore assignment patterns #4892

Closed
@NullDivision

Description

@NullDivision
  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have read the FAQ and my problem is not listed.

Repro

{
  "rules": {
    "@typescript-eslint/prefer-optional-chain": "warn"
  }
}
// your repro code case
const a: { b: string | null } = { b: null };

const x = a.b && a.b?.includes('test');

Expected Result

The code is considered valid.

Actual Result

ESLint tells me Prefer using an optional chain expression instead, as it's more concise and easier to read..

Additional Info

Versions

package version
@typescript-eslint/eslint-plugin 5.21.0
@typescript-eslint/parser 5.21.0
TypeScript 4.6.4
ESLint 8.14.0
node 16.15.0

In the above example the output of optional chaining would not be equivalent as a.b would short- circuit with a null value and return null. I'm sure this falls under the warning mentioned in the docs about edge cases but a nicer solution would be to either:

a. ignore optional chaining warnings for assignments only (using an option for the rule)
b. use type information (mentioned in #4820) to determine if the resulting value might be null

Metadata

Metadata

Assignees

No one assigned

    Labels

    package: eslint-pluginIssues related to @typescript-eslint/eslint-pluginwontfixThis will not be worked on

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions