Skip to content

Bug: [no-unnecessary-condition] False positive Checking Lookup Types #6264

Closed
@uhyo

Description

@uhyo

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.9.3&sourceType=module&code=KYDwDg9gTgLgBAMwK4DsDGMCWEVwObAwA8A8gEYBWANHANLACecoMwKAJgM5wDWjECOOQoA+ABQRKALiGUafBjPoMAlHADeAKDhw0OTvABuAQwA2SYHAC8cSRQDaCgLoBubXEyCxJ88DVadHShCJChcHws3HQBfdxgACygIAHc4FGBUgFEoJKgxAHIAIRISAFkAQnyVTVjNAhgxdUQICBkUJFNTOGiaACIEFt6VFyA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0yHJgBNK+SpPRRE0aB2iRwYAL4gtQA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA

Repro Code

export function get<Obj, Key extends keyof Obj>(obj: Obj, key: Key) {
  const value = obj[key];
  if (value) {
    return value;
  }
  throw new Error('BOOM!')
}

get({ foo: null }, "foo");

ESLint Config

module.exports = {
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module",
        "project": "./tsconfig.json"
    },
    "plugins": [
        "@typescript-eslint"
    ],
    "rules": {
        "@typescript-eslint/no-unnecessary-condition": "error"
    }
}

tsconfig

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

Expected Result

No error.

Actual Result

The rule flags if (value) as error because it thinks value is always truthy.

Additional Info

The type of value is Obj[Key] here. Maybe the rule wrongly thinks that generic lookup types are always truthy.

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