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 typenever[]
, which can't have items pushed into it as nothing is typenever
-
{}
具有类型{}
,它没有索引签名,因此无法向其添加属性¥
{}
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.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-reduce-type-parameter": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/prefer-reduce-type-parameter": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
[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[1, 2, 3].reduce<number[]>((arr, num) => arr.concat(num * 2), []);
['a', 'b'].reduce<Record<string, boolean>>(
(accum, name) => ({
...accum,
[name]: true,
}),
{},
);
Open in Playground选项
该规则不可配置。
何时不使用它
¥When Not To Use It
在使用 .reduce
创建对象时,此规则有时可能难以解决。请参阅 [prefer-reduce-type-parameter] 无法修复的报告 #3440 以了解更多详细信息。你可以考虑在这些特定情况下使用 ESLint 禁用注释