Skip to content

Bug: [no-unnecessary-condition] False positive unnecessary optional chain on nested optional values #9796

Closed
@jbs-marcus

Description

@jbs-marcus

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.5.4&fileType=.ts&code=C4TwDgpgBAcg9gE2gXigbwFBSgbQHYCGAttAJZ5QAGAJGgKpiQBOAxgQM4QA87wT5AcwB8AX1q9%2BeASMoBdAPwAuWIggBuDCKgAydFlyESUclVoAZOAHcIrDtwmDR4voJkLlDqRpEaMEAB5gcEzAUABmAK54LMCkcBTAELwAFExwcMDK8EgAlHrYLPHscAA2EAB0JXACqenA5QBi6fLlAEIETC0ARgQAXjm%2BBUWhTXBQqGkZjemDUIV4xWWV1cmjLe2d5T39s-O8UKMb41CT9WttHbtFpRVVNYcd3X0DmhgYoJAqSABMx5jYa2U-2wUA2SnyIOw23BngEGkhIn0iJ8bwCQRC4SiMTiCSSwG%2BtQyWVU3zywL2N2WNVO0zg60eW2eVwWI3Sxxpo2Zi1uK3OYMZOzeQxZB3SRwmdVp9KYXMpd1WYoZ2xeIiAA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0yHJgBNK%2BSpPRRE0aB2iRwYAL4gtQA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=true

Repro Code

type Node = {
  [name in `${Uppercase<string>}${string}`]?: Node;
} & {
  [name in `${Lowercase<string>}${string}`]?: string;
};

export function test(root: Node) {
  // Unnecessary optional chain on a non-nullish value
  console.log(root.Foo?.Bar?.baz);
  // 'root.Foo.Bar' is possibly 'undefined'
  console.log(root.Foo?.Bar.baz);
}

ESLint Config

{
  "rules": {
    "@typescript-eslint/no-unnecessary-condition": "error"
  }
}

tsconfig

{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

Expected Result

I expect the optional chaining to be allowed on line 9.

Actual Result

A lint error is emitted on line 9

Additional Info

The playground contains some more code, showing cases where things work and where things don't.

This issue is likely related to #9754

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