typescript-eslint icon indicating copy to clipboard operation
typescript-eslint copied to clipboard

Bug: [prefer-optional-chain] should report case that can be converted to optional function call `?.()`

Open kirkwaiblinger opened this issue 10 months ago • 1 comments

Before You File a Bug Report Please Confirm You Have Done The Following...

  • [x] I have tried restarting my IDE and the issue persists.
  • [x] I have updated to the latest version of the packages.
  • [x] I have searched for related issues and found none that matched my issue.
  • [x] I have read the FAQ and my problem is not listed.

Playground Link

https://typescript-eslint.io/play/#ts=5.6.3&fileType=.tsx&code=CYUwxgNghgTiAEYD2A7AzgF3gMyUgXPAN4BQ88AtiBgBZLCECuKo2AliiMPAD7wAU-AJTwAvAD54ANyRtgQkgF8SJXEgB0VWvXgAyXTjybqdYMIDcQA&eslintrc=N4AhCgwIgJwVwDYFMDOUBcJiTCKABAFwE8AHVAYxgEtTCBaVBagO0IHpSYkAzJGegHs61QSwCGCehQAW41hjwB3cTBZQcAX3CagA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eFYDAruuGAL4g9A&tokens=false

Repro Code

declare const foo: {
  method: undefined | (() => void)
}

foo.method && foo.method();

ESLint Config

module.exports = {  
  "rules": {
    "@typescript-eslint/prefer-optional-chain": "warn"
  }
}

tsconfig

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

Expected Result

I expect that the rule should report and suggest foo.method?.().

Actual Result

No report

Additional Info

This is specifically implied in the docs examples with the line foo && foo.a && foo.a.b && foo.a.b.method && foo.a.b.method();

Relates to #9605

kirkwaiblinger avatar Jun 04 '25 21:06 kirkwaiblinger

Oh, this appears to be a case specifically around the return type being void...

(playground)

declare const foo: {
  returnsVoid: undefined | (() => void)
  returnsString: undefined | (() => string)
}

// does not report
foo.returnsVoid && foo.returnsVoid();
// reports
foo.returnsString && foo.returnsString();

At least in cases where the return value is not used, I'd think we should report these kinds of expressions. This is a prime use case for ?.(), since patterns like context.optionalCallback?.(); arise naturally.

kirkwaiblinger avatar Jun 04 '25 22:06 kirkwaiblinger