Skip to main content

prefer-reduce-type-parameter

Enforce using type parameter when calling Array#reduce instead of using a type assertion.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict-type-checked" 可启用此规则。

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

通常使用泛型类型(例如数组或对象)作为初始值来调用 Array#reduce。由于这些值为空,因此它们的类型不可用:

¥It's common to call Array#reduce with a generic type, such as an array or object, as the initial value. Since these values are empty, their types are not usable:

  • [] 具有类型 never[],由于没有任何东西是 never 类型,因此无法将项目推入其中

    ¥[] has type never[], which can't have items pushed into it as nothing is type never

  • {} 具有类型 {},它没有索引签名,因此无法向其添加属性

    ¥{} has type {}, which doesn't have an index signature and so can't have properties added to it

解决此问题的常见方法是对初始值使用 as 断言。虽然这可行,但它不是最佳解决方案,因为类型断言会对底层类型产生微妙的影响,从而导致错误溜进去。

¥A common solution to this problem is to use an as assertion on the initial value. While this will work, it's not the most optimal solution as type assertions have subtle effects on the underlying types that can allow bugs to slip in.

更好的解决方案是将类型作为泛型类型参数显式传递给 Array#reduce。这意味着 TypeScript 不必尝试推断类型,并避免了断言带来的常见陷阱。

¥A better solution is to pass the type in as a generic type argument to Array#reduce explicitly. This means that TypeScript doesn't have to try to infer the type, and avoids the common pitfalls that come with assertions.

在这些情况下,此规则可能不太有用。它将建议将断言的类型作为泛型类型参数传递给 Array#reduce

¥This rule looks for calls to Array#reduce, and reports if an initial value is being passed & asserted. It will suggest instead pass the asserted type to Array#reduce as a generic type argument.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-reduce-type-parameter": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

[1, 2, 3].reduce((arr, num) => arr.concat(num * 2), [] as number[]);

['a', 'b'].reduce(
(accum, name) => ({
...accum,
[name]: true,
}),
{} as Record<string, boolean>,
);
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

在使用 .reduce 创建对象时,此规则有时可能难以解决。请参阅 [prefer-reduce-type-parameter] 无法修复的报告 #3440 以了解更多详细信息。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

¥This rule can sometimes be difficult to work around when creating objects using a .reduce. See [prefer-reduce-type-parameter] unfixable reporting #3440 for more details. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

'## 资源'