sindresorhus/eslint-plugin-unicorn
`explicit-length-check`: false positive when checking presence of property in TypeScript
Closed
#2,217 opened on Nov 5, 2023
bughelp wantedtypes
Repository metrics
- Stars
- (5,022 stars)
- PR merge metrics
- (Avg merge 1d 16h) (399 merged PRs in 30d)
Description
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:
- If we had type-awareness, we could ignore this, but I'm assuming we don't.
- We could ignore the pattern
obj.size && obj.size > 0on 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.