Typescript:用一个初始值开始一个reduce语句?



我试图写一个相当复杂的减少语句,我把数组和数组数组变成对象数组。这是我的起始数组和我想要结束的类型:

const fruits = ['apple', 'banana', 'pear', 'plum', 'grape'];
const fruitConsumers = [
['Jeremy, Claude', '', '', 'Helen, Benny, Sophie', ''],
['', 'Francis, Paul', '', 'Alice', 'Bob, Tracy', 'Lacey, Stacey'],
];
type FruitPersonMap = {
apple: string[],
banana: string[],
pear: string[],
plum: string[],
grape: string[],
people?: {
name: string,
fruit: string,
}[]
}

在大多数情况下,这工作得很好,除了我想在最后拥有所有人和他们的水果的数组的部分。由于某些原因,打字稿不喜欢这样。下面是我的函数:

const makeFruitPersonMap = (fruits: string[], consumers: string[][]): FruitPersonMap[] => {
return consumers.map(consumerSet => {
return consumerSet.reduce((acc, val: string, i: number) => {
// the nth item in a consumer list will always correspond to the nth fruit
const currentFruit = fruits[i];
// turn the people into an array instead of a comma separated string
const peopleList = val.split(',').map(name => name.trim());
// turn the array of people into an array of objects with keys name, fruit
const peopleWithFruit = peopleList.map(person => ({
name: person,
fruit: currentFruit,
}))
// add the current key to the accumulator and add the people objects onto the list.
return {
...acc,
[currentFruit]: peopleList,
people: peopleWithFruit ? acc.people.concat(peopleWithFruit) : acc.people
}
}, { people: [] }) as FruitPersonMap
})
};

这样做会给我一个错误:Conversion of type '{ people: never[]; }' to type 'FruitPersonMap' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first

我不明白的是为什么people键是给定类型never[]。将事物连接到people数组也给了我这个问题,这对我来说很奇怪。我还尝试在回调函数(if (!acc.people) acc.people = [])中添加people键,但随后我得到acc.people不存在于{}上的错误。我的意思是,我同意设置people键的值是一种糟糕的方式,但我已经检查了它是否存在。这是怎么回事!

所以我想我的问题是双重的。为什么Typescript对这种处理reduce的特殊方式不满意,是否有一种方法可以设置reduce的初始值,而不会导致这个问题?

我在输入所有问题后大约30秒就明白了。

新类型:

type PeopleList = {
people: {
name: string,
fruit: string,
}[]
}

更新功能:

const testFunc = (fruits: string[], consumers: string[][]) => {
return consumers.map(consumerSet => {
return consumerSet.reduce((acc, val: string, i: number) => {
const currentFruit = fruits[i];
const peopleList = val.split(',').map(name => name.trim());
const peopleWithFruit = peopleList.map(person => ({
name: person,
fruit: currentFruit,
}))
return {
...acc,
[currentFruit]: peopleList,
people: peopleWithFruit ? acc.people.concat(peopleWithFruit) : acc.people
}
}, { people: [] } as PeopleList) as FruitPersonMap
})
};

注意{ people: [] } as PeopleList:将类型设置为与FruitPersonMap重叠的初始值可以修复它。

我想我应该把这个问题留下,以防其他人遇到这个问题,像我一样感到困惑。

相关内容

最新更新