Skip to content

feat(eslint-plugin): [no-misused-promises] check array predicate return #9955

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/eslint-plugin/docs/rules/no-misused-promises.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ if (promise) {

const val = promise ? 123 : 456;

[1, 2, 3].filter(() => promise);

while (promise) {
// Do something
}
Expand All @@ -152,6 +154,9 @@ if (await promise) {

const val = (await promise) ? 123 : 456;

const returnVal = await promise;
[1, 2, 3].filter(() => returnVal);

while (await promise) {
// Do something
}
Expand Down
23 changes: 23 additions & 0 deletions packages/eslint-plugin/src/rules/no-misused-promises.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import * as ts from 'typescript';
import {
createRule,
getParserServices,
isArrayMethodCallWithPredicate,
isFunction,
isRestParameterDeclaration,
nullThrows,
Expand All @@ -31,6 +32,7 @@ interface ChecksVoidReturnOptions {

type MessageId =
| 'conditional'
| 'predicate'
| 'spread'
| 'voidReturnArgument'
| 'voidReturnAttribute'
Expand Down Expand Up @@ -91,6 +93,7 @@ export default createRule<Options, MessageId>({
voidReturnVariable:
'Promise-returning function provided to variable where a void return was expected.',
conditional: 'Expected non-Promise value in a boolean conditional.',
predicate: 'Expected a non-Promise value to be returned.',
spread: 'Expected a non-Promise value to be spreaded in an object.',
},
schema: [
Expand Down Expand Up @@ -175,6 +178,7 @@ export default createRule<Options, MessageId>({
checkConditional(node.argument, true);
},
WhileStatement: checkTestConditional,
'CallExpression > MemberExpression': checkArrayPredicates,
};

checksVoidReturn = parseChecksVoidReturn(checksVoidReturn);
Expand Down Expand Up @@ -322,6 +326,25 @@ export default createRule<Options, MessageId>({
}
}

function checkArrayPredicates(node: TSESTree.MemberExpression): void {
const parent = node.parent;
if (parent.type === AST_NODE_TYPES.CallExpression) {
const callback = parent.arguments.at(0);
if (
callback &&
isArrayMethodCallWithPredicate(context, services, parent)
) {
const type = services.esTreeNodeToTSNodeMap.get(callback);
if (returnsThenable(checker, type)) {
context.report({
messageId: 'predicate',
node: callback,
});
}
}
}
}

function checkArguments(
node: TSESTree.CallExpression | TSESTree.NewExpression,
): void {
Expand Down
23 changes: 5 additions & 18 deletions packages/eslint-plugin/src/rules/no-unnecessary-condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
getParserServices,
getTypeName,
getTypeOfPropertyOfName,
isArrayMethodCallWithPredicate,
isIdentifier,
isNullableType,
isTypeAnyType,
Expand Down Expand Up @@ -458,26 +459,12 @@ export default createRule<Options, MessageId>({
checkNode(node.test);
}

const ARRAY_PREDICATE_FUNCTIONS = new Set([
'filter',
'find',
'some',
'every',
]);
function isArrayPredicateFunction(node: TSESTree.CallExpression): boolean {
const { callee } = node;
return (
// looks like `something.filter` or `something.find`
callee.type === AST_NODE_TYPES.MemberExpression &&
callee.property.type === AST_NODE_TYPES.Identifier &&
ARRAY_PREDICATE_FUNCTIONS.has(callee.property.name) &&
// and the left-hand side is an array, according to the types
(nodeIsArrayType(callee.object) || nodeIsTupleType(callee.object))
);
}
function checkCallExpression(node: TSESTree.CallExpression): void {
// If this is something like arr.filter(x => /*condition*/), check `condition`
if (isArrayPredicateFunction(node) && node.arguments.length) {
if (
isArrayMethodCallWithPredicate(context, services, node) &&
node.arguments.length
) {
const callback = node.arguments[0];
// Inline defined functions
if (
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export * from './scopeUtils';
export * from './types';
export * from './isAssignee';
export * from './getFixOrSuggest';
export * from './isArrayMethodCallWithPredicate';

// this is done for convenience - saves migrating all of the old rules
export * from '@typescript-eslint/type-utils';
Expand Down
43 changes: 43 additions & 0 deletions packages/eslint-plugin/src/util/isArrayMethodCallWithPredicate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { getConstrainedTypeAtLocation } from '@typescript-eslint/type-utils';
import type {
ParserServicesWithTypeInformation,
TSESTree,
} from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import type { RuleContext } from '@typescript-eslint/utils/ts-eslint';
import * as tsutils from 'ts-api-utils';

import { getStaticMemberAccessValue } from './misc';

const ARRAY_PREDICATE_FUNCTIONS = new Set([
'filter',
'find',
'findIndex',
'findLast',
'findLastIndex',
'some',
'every',
]);

export function isArrayMethodCallWithPredicate(
context: RuleContext<string, unknown[]>,
services: ParserServicesWithTypeInformation,
node: TSESTree.CallExpression,
): boolean {
if (node.callee.type !== AST_NODE_TYPES.MemberExpression) {
return false;
}

const staticAccessValue = getStaticMemberAccessValue(node.callee, context);

if (!staticAccessValue || !ARRAY_PREDICATE_FUNCTIONS.has(staticAccessValue)) {
return false;
}

const checker = services.program.getTypeChecker();
const type = getConstrainedTypeAtLocation(services, node.callee.object);
return tsutils
.unionTypeParts(type)
.flatMap(part => tsutils.intersectionTypeParts(part))
.some(t => checker.isArrayType(t) || checker.isTupleType(t));
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

53 changes: 53 additions & 0 deletions packages/eslint-plugin/tests/rules/no-misused-promises.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1047,6 +1047,10 @@ interface MyInterface extends MyCall, MyIndex, MyConstruct, MyMethods {
'const notAFn3: boolean = true;',
'const notAFn4: { prop: 1 } = { prop: 1 };',
'const notAFn5: {} = {};',
`
const array: number[] = [1, 2, 3];
array.filter(a => a > 1);
`,
],

invalid: [
Expand Down Expand Up @@ -2269,5 +2273,54 @@ interface MyInterface extends MyCall, MyIndex, MyConstruct, MyMethods {
},
],
},
{
code: `
declare function isTruthy(value: unknown): Promise<boolean>;
[0, 1, 2].filter(isTruthy);
`,
errors: [
{
line: 3,
messageId: 'predicate',
},
],
},
{
code: `
const array: number[] = [];
array.every(() => Promise.resolve(true));
`,
errors: [
{
line: 3,
messageId: 'predicate',
},
],
},
{
code: `
const array: (string[] & { foo: 'bar' }) | (number[] & { bar: 'foo' }) = [];
array.every(() => Promise.resolve(true));
`,
errors: [
{
line: 3,
messageId: 'predicate',
},
],
},
{
code: `
const tuple: [number, number, number] = [1, 2, 3];
tuple.find(() => Promise.resolve(false));
`,
options: [{ checksConditionals: true }],
errors: [
{
line: 3,
messageId: 'predicate',
},
],
},
],
});
Original file line number Diff line number Diff line change
Expand Up @@ -1291,11 +1291,13 @@ function truthy() {
function falsy() {}
[1, 3, 5].filter(truthy);
[1, 2, 3].find(falsy);
[1, 2, 3].findLastIndex(falsy);
`,
output: null,
errors: [
ruleError(6, 18, 'alwaysTruthyFunc'),
ruleError(7, 16, 'alwaysFalsyFunc'),
ruleError(8, 25, 'alwaysFalsyFunc'),
],
},
// Supports generics
Expand Down
Loading