Skip to content

Commit 111c244

Browse files
authored
fix(eslint-plugin): [no-unnecessary-condition] false positive when array predicate returns unknown (typescript-eslint#2772)
1 parent 3e4a0ed commit 111c244

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

packages/eslint-plugin/src/rules/no-unnecessary-condition.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,10 @@ export default createRule<Options, MessageId>({
450450
// Not a callable function
451451
return;
452452
}
453+
// Predicate is always necessary if it involves `any` or `unknown`
454+
if (returnTypes.some(t => isTypeAnyType(t) || isTypeUnknownType(t))) {
455+
return;
456+
}
453457
if (!returnTypes.some(isPossiblyFalsy)) {
454458
return context.report({
455459
node: callback,

packages/eslint-plugin/tests/rules/no-unnecessary-condition.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,14 @@ function length(x: string) {
235235
function nonEmptyStrings(x: string[]) {
236236
return x.filter(length);
237237
}
238+
239+
// filter-like predicate
240+
function count(
241+
list: string[],
242+
predicate: (value: string, index: number, array: string[]) => unknown,
243+
) {
244+
return list.filter(predicate).length;
245+
}
238246
`,
239247
// Ignores non-array methods of the same name
240248
`

0 commit comments

Comments
 (0)