Skip to content

useIterableCallbackReturn

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"suspicious": {
"useIterableCallbackReturn": "error"
}
}
}
}

¥Description

强制可迭代回调函数返回值保持一致。

¥Enforce consistent return values in iterable callbacks.

此规则确保传递给某些可迭代方法的回调函数始终返回一个值或从不返回一个值,具体取决于方法的要求。

¥This rule ensures that callbacks passed to certain iterable methods either always return a value or never return a value, depending on the method’s requirements.

请注意,异步回调和生成器回调会被忽略,因为它们分别始终返回 PromiseGenerator

¥Note that async and generator callbacks are ignored as they always return Promise or Generator respectively.

¥Methods and Their Requirements

以下方法的回调函数需要返回值:

¥The following methods require a return in their callback:

  • every

  • filter

  • find

  • findIndex

  • findLast

  • findLastIndex

  • flatMap

  • map

  • reduce

  • reduceRight

  • some

  • sort

  • toSortedfrom(在 Array 上调用时)

    ¥toSortedfrom (when called on Array)

方法 forEach 不允许返回值。

¥A return value is disallowed in the method forEach.

¥Examples

¥Invalid

[].map(() => {
// Missing return value
});
code-block.js:1:4 lint/suspicious/useIterableCallbackReturn ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This callback passed to map() iterable method should always return a value.

> 1 │ [].map(() => {
^^^
2 │ // Missing return value
3 │ });

Add a return with a value to this callback.

[].forEach(() => {
return 1; // Should not return a value
});
code-block.js:1:4 lint/suspicious/useIterableCallbackReturn ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This callback passed to forEach() iterable method should not return a value.

> 1 │ [].forEach(() => {
^^^^^^^
2 │ return 1; // Should not return a value
3 │ });

Either remove this return or remove the returned value.

> 1 │ [].forEach(() => {

> 2 │ return 1; // Should not return a value
^^^^^^^
3 │ });
4 │

¥Valid

[].map(() => {
return 1; // Correctly returns a value
});
[].forEach(() => {
// No return value, which is correct
});
[].forEach(() => void null); // Void return value, which doesn't trigger the rule

¥Related links