sindresorhus/eslint-plugin-unicorn

`explicit-length-check`: false positive when checking presence of property in TypeScript

Chiusa

#2217 aperta il 5 nov 2023

 (2 commenti) (0 reazioni) (0 assegnatari)JavaScript (468 fork)user submission
bughelp wantedtypes

Metriche repository

Star
 (5022 stelle)
Metriche merge PR
 (Merge medio 4h 30m) (26 PR mergiate in 30 g)

Descrizione

In TypeScript, for a property that could be null / undefined / number, we need to check if the property exists first before performing a comparison on it, like this:

const obj: { size: number | null } = { size: 123 /* hardcoded for example */ };
if (obj.size && obj.size > 0) {
  console.log();
}

But this gets flagged by explicit-length-check and autofixed to:

const obj: { size: number | null } = { size: 123 /* hardcoded for example */ };
if (obj.size > 0 && obj.size > 0) {
  console.log();
}

Which hits the original TypeScript error:

'obj.size' is possibly 'null'.ts(18047)

Some fix ideas:

  1. If we had type-awareness, we could ignore this, but I'm assuming we don't.
  2. We could ignore the pattern obj.size && obj.size > 0 on the assumption that the first part of the expression is a presence check and that it would it would be redundant to autofix the first part of the expression to another comparison.

Guida contributor