typescript/prefer-reduce-type-parameter 风格
它的作用
此规则建议在 Array.reduce 中使用类型参数来指定累加器的类型,而不是进行类型转换。
为什么这是不好的?
Array.reduce 可以通过泛型类型参数来指定累加器的类型。相比于对结果进行类型转换,这种方式提供了更好的类型安全性,并且更明确地表达了预期的类型。
示例
以下为 错误 的代码示例:
ts
const numbers = [1, 2, 3];
// 对结果进行类型转换
const sum = numbers.reduce((acc, val) => acc + val, 0) as number;
// 对累加器使用类型断言
const result = [1, 2, 3].reduce((acc: string[], curr) => {
acc.push(curr.toString());
return acc;
}, [] as string[]);以下为 正确 的代码示例:
ts
const numbers = [1, 2, 3];
// 使用类型参数
const sum = numbers.reduce<number>((acc, val) => acc + val, 0);
// 复杂类型的类型参数
const result = [1, 2, 3].reduce<string[]>((acc, curr) => {
acc.push(curr.toString());
return acc;
}, []);
// 当 TypeScript 能够推断出类型时,无需添加类型参数
const simpleSum = numbers.reduce((acc, val) => acc + val, 0);
// 带有类型参数的对象累加器
interface Count {
[key: string]: number;
}
const counts = ["a", "b", "a"].reduce<Count>((acc, item) => {
acc[item] = (acc[item] || 0) + 1;
return acc;
}, {});如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/prefer-reduce-type-parameter": "error"
}
}bash
oxlint --type-aware --deny typescript/prefer-reduce-type-parameter