Skip to content

Bug: [no-unnecessary-condition] False positive when using the iteration variable to access object fields with different types #12556

Description

@lantw44

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.
  • If I used AI assistance to prepare this issue, I have reviewed and followed the AI Contribution Policy.

Playground Link

https://typescript-eslint.io/play/#ts=6.0.2&fileType=.tsx&code=C4TwDgpgBAYglhANgEwM5QLxQN4CgpQAWSiA9gPwBcUAdgK4C2ARhAE4Dc%2BUA7qaylShNSpRBACGNTgF9cuMcCgAzBClTV4SNJhzTOuJXygAKAMakaqRQGsIIKKSVQA2gHJiiMq4A0UV735kVwBdKHF0c0tgAEocLhUtVGdbEFDyciw6GmQIFRoIZBkgA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0yHJgBNK%2BSpPRRE0aB2iRwYAL4gtQA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

type Fields = {
  hello?: number;
  world?: boolean;
}

let fields: Fields = {};

for (const key of ['hello', 'world'] as const) {
  fields[key] ??= undefined;
}

ESLint Config

module.exports = {
  parser: "@typescript-eslint/parser",
  rules: {
    "@typescript-eslint/no-unnecessary-condition": "error",
  },
};

tsconfig

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

Expected Result

No error. Replacing the ['hello', 'world'] array with either ['hello'] or ['world'] produces no error.

Actual Result

The fields[key] ??= undefined line causes the error:
Unnecessary conditional, left-hand side of ?? operator is always null or undefined.

Additional Info

No response

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