如何在Typescript中定义Array.reduce方法



TypeScript:中的reduce方法有问题

const items = {a: 10, b:20, c: 30}
const itemsTotal = Object.keys(items).reduce((accumulator: number, key: keyof typeof items ) => {
return accumulator + items[key]
}, 0)

我一直收到Typescript错误:

类型为"的参数(累加器:数字,键:"a"|"b"|"c"(=>number"不可分配给类型为"的参数(previousValue:string,currentValue:string,currentIndex:number,array:string[](=>字符串'。

Types of parameters 'accumulator' and 'previousValue' are incompatible.***

似乎我需要定义reduce方法的类型,但如何定义?

Object.keys返回一个string[],因此不能应用一个要求keyof typeof items的reducer函数。

您可以使用类型断言,因为您知道它是有效的:

const items = {a: 10, b:20, c: 30};
const itemsTotal = Object.keys(items).reduce((accumulator, key) => {
return accumulator + items[key as keyof typeof items];
}, 0);

游乐场

但你不需要钥匙,只需使用Object.values:

const items = {a: 10, b:20, c: 30};
const itemsTotal = Object.values(items).reduce((accumulator, value) => {
return accumulator + value;
}, 0);

游乐场

(但坦率地说,我只想使用一个简单的循环。(

不是最干净的解决方案,但您可以使用以下片段:

const items = { a: 10, b: 20, c: 30 }
const itemsTotal = Object.keys(items).reduce((accumulator, key) => {
return accumulator + items[key as keyof typeof items]
}, 0)

关键是将key转换为keyof typeof items

将项目定义为stringnumber的记录。对于reduce方法,将清楚的是该项是number

const items: Record<string, number> = {a: 10, b: 20, c: 30}
const itemsTotal = Object.keys(items).reduce((accumulator: number, key: string) => {
return accumulator + items[key];
}, 0)

也可以跳过reduce正文中的大括号。

Object.keys(items).reduce((acc: number, key: string) => acc + items[key], 0)

更重要的是,您可以跳过reduce中的类型指定,因为您的items已经在Record中定义为数字。

Object.keys(items).reduce((acc, key) => acc + items[key], 0)

编辑

您可以跳过累加器初始化。在这种情况下,CCD_ 17从第一项开始。

Object.values(items).reduce( (acc, item) => acc + item )

最快的解决方案是使用forof,因为没有函数调用:

let sum = 0
for (const item of Object.values(items)) {
sum += item;
}

最新更新