gpt4 book ai didi

javascript - Typescript 中的 reduce() 函数实例化空对象

转载 作者:行者123 更新时间:2023-12-05 02:36:00 24 4
gpt4 key购买 nike

我正在尝试将我的 Javascript 函数转换为它的 Typescript 版本,但我无法摆脱读取的带下划线的代码 acc[curr.name] (在 VSCode 中)。将鼠标悬停在上面时说:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.No index signature with a parameter of type 'string' was found on type '{}'.

我按键名计算出现次数。

我应该在哪里定义类型,为什么空对象或带数字的对象不起作用。我不确定如何解决它,因为我尝试了多种方法,例如:

data.reduce<{}>()data.reduce<{property: number}>()

代码:

const data = [
{ name: "name1", },
{ name: "name1", },
{ name: "name1", },
{ name: "name1", },
{ name: "name2", },
{ name: "name2", },
{ name: "name2", },
{ name: "name1", },
];

// count data by key name
const resultData = data.reduce((acc, curr) => {
return acc[curr.name] ? ++acc[curr.name] : (acc[curr.name] = 1), acc;
}, {});

运行结果:

const resultData = {
name1: 4,
name2: 3,
name3: 1,
};

最佳答案

设置索引签名,如 data.reduce<{ [index: string]: number }>

引用:https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures

const resultData = data.reduce<{ [index: string]: number }>((acc, curr) => {
return acc[curr.name] ? ++acc[curr.name] : (acc[curr.name] = 1), acc;
}, {});

或者您可以使用 as具有初始值的关键字。

const resultData = data.reduce((acc, curr) => {
return acc[curr.name] ? ++acc[curr.name] : (acc[curr.name] = 1), acc;
}, {} as { [index: string]: number });

关于javascript - Typescript 中的 reduce() 函数实例化空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70373386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com