Skip to content

Bug: [no-unnecessary-condition] using nullish coalescing assignment operator in reduce seems to flag false positive #7610

@treskilion

Description

@treskilion

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=.ts&code=MYewdgzgLgBBIFsCmBBATmghgTxgXhgG0BYAKBhgG8YBLAEwC4YAiegeTCWYBoYpsADkibN%2BQlMxgBfbmQrV6I9px59BwlmKQBhSTLlVajFvQAqAdxCqtIrROmzyhxSboWrvG5vUAhPY-kjJTcACzQkLk91W3V7KTIAXQBuMjItGABlRCRTdXwYACUkUDQ6AB5oNBowAHNeSuqawgSAPhTSMnhkdCxsADpwugBXYCQyrORcoRaAChmkMCgqpAheGigkLA2kAEp8FqoDUEhYBToooWl89c3Mbfaj8GgYBaXcAlfliEJ6BJgAfn%2BBGa7Qon36AiGEBCMy0OweTnCUCGaDAL0WX3aMioUnhQA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0yHJgBNK%2BSpPRRE0aB2iRwYAL4gtQA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

const someArray = [
  { id: "idOne", type: "typeA" },
  { id: "idOne", type: "typeC" },
  { id: "idTwo", type: "typeA" },
  { id: "idTwo", type: "typeB" },
  { id: "idThree", type: "typeA" }
];

type SomeType = Record<string, string[]>;

someArray.reduce<SomeType>((entries, iteratee) => {
  const { id, type } = iteratee;

  const entry = entries[id] ??= [];
  entry.push(type);

  return entries;
}, {});

ESLint Config

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

tsconfig

{
  "compilerOptions": {
    "strictNullChecks": true,
    "noUncheckedIndexedAccess": true
  }
}

Expected Result

Since entries has a type of Record<string, string[]> item fetched via index will give either an item or undefined.
TypeScript seems to recognize this
image

Actual Result

@typescript-eslint is under the impression that it will always get a result from accessing the object via index and flags the use of ??= as an unnecessary condition.

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingduplicateThis 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