Skip to content

[no-unnecessary-condition] False positive unnecessary optional chain on nested void values #9754

Open
@lukekarrys

Description

@lukekarrys

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.

Issue Description

Given the following code, I would expect it to lint successfully:

const maybe = <T>(v: T): T | void => v

const a = maybe({
  key1: {
    key2: maybe({
      i: 1,
    }),
  },
})?.key1.key2?.i
//           ^
// 9:14  error  Unnecessary optional chain on a non-nullish value  @typescript-eslint/no-unnecessary-condition

In my reproduction the second optional chain is removed if I run with --fix but then TypeScript errors with the following:

> tsc --noEmit

index.ts:9:15 - error TS2339: Property 'i' does not exist on type 'void | { i: number; }'.
  Property 'i' does not exist on type 'void'.

9 })?.key1.key2.i
                ~


Found 1 error in index.ts:9

I also want to note that this behavior does not occur if the value could be null only void. It successfully lints if I change the return of maybe to T | null.

In my reproduction I also tried to narrow it down as far as I could and found that these examples lint successfully:

// This lints fine
const b = maybe({
  key1: maybe({
    i: 1,
  }),
})?.key1?.i

// So does this
const c = {
  key1: {
    key2: maybe({
      i: 1,
    }),
  },
}.key1.key2?.i

Reproduction Repository Link

https://gist.github.com/lukekarrys/979ea0dd68b52937e9a257b4d2c9c293

Repro Steps

git clone https://gist.github.com/lukekarrys/979ea0dd68b52937e9a257b4d2c9c293
npm install
npm run lint

Versions

package version
@typescript-eslint/eslint-plugin 8.0.1
TypeScript 5.5.4
ESLint 9.8.0
node 22.4.0

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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions