Skip to main content

prefer-reduce-type-parameter

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

🔒

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 类型
  • {} 具有类型 {},该类型没有索引签名,因此无法添加属性

此问题的常见解决方案是对初始值使用 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 casting.

此规则查找对 Array#reduce 的调用,并报告是否正在传递和断言初始值。 它会建议将断言类型作为泛型类型参数传递给 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.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-reduce-type-parameter": "error"
}
};
在线运行试试这个规则 ↗

示例

[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

何时不使用它

使用 .reduce 创建对象时,有时很难解决此规则。 See [prefer-reduce-type-parameter] unfixable reporting #3440 for more details. 你可以考虑在这些特定情况下使用 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.

选项

该规则不可配置。

资源