[英]How can I define Array.reduce method in Typescript?
I have a problem with the reduce
method in TypeScript:我对 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)
I keep receiving the Typescript error:我不断收到 Typescript 错误:
Argument of type '(accumulator: number, key: "a" | "b" | "c") => number' is not assignable to parameter of type '(previousValue: string, currentValue: string, currentIndex: number, array: string[]) => string'.
'(accumulator: number, key: "a" | "b" | "c") => number' 类型的参数不可分配给 '(previousValue: string, currentValue: string, currentIndex: number, array:字符串[]) => 字符串'。
Types of parameters 'accumulator' and 'previousValue' are incompatible.***
It seems that I need to define the type of the reduce
method, but how?看来我需要定义
reduce
方法的类型,但是怎么做呢?
Object.keys
returns a string[]
, so you can't apply a reducer function that expects a keyof typeof items
to it. Object.keys
返回一个string[]
,所以你不能应用一个减速器 function ,它需要一个keyof typeof items
。
You could use a type assertion, since you know it's valid:您可以使用类型断言,因为您知道它是有效的:
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);
...but you don't need the key anyway, just use Object.values
: ...但无论如何您都不需要密钥,只需使用
Object.values
:
const items = {a: 10, b:20, c: 30};
const itemsTotal = Object.values(items).reduce((accumulator, value) => {
return accumulator + value;
}, 0);
(But frankly I'd just use a simple loop .) (但坦率地说,我只是使用一个简单的循环。)
Define your items as a Record of string
to number
.将您的项目定义为
string
到number
的记录。 It will be clear for the reduce
method that the item is a number
.对于
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)
You can also skip the braces in the reduce
body.您也可以跳过
reduce
主体中的大括号。
Object.keys(items).reduce((acc: number, key: string) => acc + items[key], 0)
Even more, you can skip the type designations in the reduce
because your items
are already defined as numbers in the Record
.更重要的是,您可以跳过
reduce
中的类型指定,因为您的items
已经在Record
中定义为数字。
Object.keys(items).reduce((acc, key) => acc + items[key], 0)
Not the cleanest solution but you can use this snippet:不是最干净的解决方案,但您可以使用此代码段:
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 point is to cast key
to keyof typeof items
关键点是将
key
转换为keyof typeof items
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.