Skip to content

[no-unnecessary-condition] False error on uninitialized variable #4513

Closed
@Retro64

Description

@Retro64
  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have read the FAQ and my problem is not listed.

Playground

{
  "rules": {
      "@typescript-eslint/no-unnecessary-condition": [
      "error"
    ],
  }
}
let foo: string;

const setFoo = (): void => {
  if (foo?.length < 1) {
    foo = 'foo';
  }
};

tsconfig

{
  "compilerOptions": {
    "outDir": "./lib",
    "module": "commonjs",
    "target": "es2015",
    "lib": ["es6", "es7"],
    "sourceMap": true,
    "allowJs": false,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strict": true,
    "strictNullChecks": true,
    "suppressImplicitAnyIndexErrors": true,
    "noUnusedLocals": true,
    "noErrorTruncation": true,
    "pretty": true,
    "declaration": true
  },
  "include": [
    "src/**/*"
  ]
}

Expected Result

Existence check on a possibly uninitialized variable should not trigger no-unnecessary-condition

For sure, the type might be extended to let foo = string | undefined; as workaround, but that actually looks a bit uncommon for a let definition, where not initializing might be intended.

Actual Result
Unnecessary optional chain on a non-nullish value @typescript-eslint/no-unnecessary-condition

Versions

package version
@typescript-eslint/eslint-plugin 5.10.0
@typescript-eslint/parser 5.10.0
TypeScript 4.5.5
ESLint 8.7.0
ts-node 10.4.0

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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions