Skip to content

Bug: [no-unnecessary-condition] false positive on indexed access of a generic type #7850

Closed
@mx-bernhard

Description

@mx-bernhard

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=GYVwdgxgLglg9mABAUwB4EMC2AHANsgHgBUVUpkwATAZ0TgCMArZaAPgAoAoRRdAJwDmALkREANN0QBrZAE8RM2XGCienAJQiAbnBiVEAb0kQE1KInoBGRAF5eggNqKAuogCEdsCFy4A3MdNzegAmW3sBJzlXAH5oxAByYHQfenQIKXj-AF9OEzAzOhEDRGA4OBEzPhgwAQAfLx9ELLDi0vLEBtwm-zQsPGR2ODEEtvj1XyA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0yHJgBNK%2BSpPRRE0aB2iRwYAL4gtQA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eFYDArugDTg10NM8AOXapUAYQAW6aAGsylDt160isAKpF2JdABMACgENMh%2BOjxYFYAGaHUOnjShrN2vQBlY0O1dv3lTpAuRNDScnoAkkS66AAeegCC0NDoJFZKvAC%2BIJlAA&tokens=false

Repro Code

function example<T extends object>(
  arg: T,
  key: keyof T  
): void {
  const b1 = arg[key] != null;
  const b2 = arg[key] ?? 'fallback';
}
const o: { foo: string|null } = { foo: null };
example(o, 'foo');

ESLint Config

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

tsconfig

{
  "compilerOptions": {
    "strict": true
  }
}

Expected Result

No error should be reported since it is possible to supply null values on properties of the incoming object in the example.

Actual Result

An error gets reported saying that null and the value of the type that it is compared with does not have any overlap:

Unnecessary conditional, the types have no overlap. 5:14 - 5:30

Unnecessary conditional, expected left-hand side of `??` operator to be possibly null or undefined. 6:14 - 6:22

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