Skip to content

Bug: prefer-optional-chain throws error unexpected Identifier #5556

@revelt

Description

@revelt

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=4.7.4&sourceType=module&code=MYewdgzgLgBAZiEMC8MBEBDARsNBuAKFElgEsUYAmQgQgRAG1yBaGARgF0A6AGwFMwAcygALGAB9xMUniA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Y6RAM0WloHsalfkwCG8WmQAWo5uii9o-aJHBgAviHVA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA

Repro Code

const foo = "abc";
const i = 2;
!foo[i - 1].length || i;

ESLint Config

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

tsconfig

{
  "compilerOptions": {
    // ...
  }
}

Expected Result

I expect the rule not to cause ESLint to throw; it is a valid code and lint rule "prefer-optional-chain" does not apply there.

Actual Result

Rule causes an ESLint throw error.

Additional Info

The minimal pattern !foo[i - 1].length || i; is a bit obscure, so here's the actual source code I distilled it from:

const padLeftIfTheresOnTheLeft = [':'];
// ...
if (
  !source[y - 3].trim().length ||
  padLeftIfTheresOnTheLeft.some((val) =>
    source
      .slice(startPoint, y - 2)
      .trim()
      .endsWith(val)
  )
) {
  // ...
}

it's an npm package generate-atomic-css, line 742 in the source: https://github.com/codsen/codsen/blob/main/packages/generate-atomic-css/src/util.ts#L742

Also, I can confirm the linting rule was not breaking on @typescript-eslint/eslint-plugin previous version 5.33.1, I was trying to bump it to 5.35.1 and only now it throws.

Versions

package version
@typescript-eslint/eslint-plugin 5.35.1
@typescript-eslint/parser 5.35.1
TypeScript 4.7.4
ESLint 8.22.0
node 16.17.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    duplicateThis issue or pull request already existspackage: 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