reduce()的累加器和当前参数应该如何输入?



要减少的累加器和当前参数应该如何输入?

interface CountriesContinent {
continent: string;
countries: string[];
}
interface ZebraInCountry {
countryName: string;
population: number;
}
interface ContinentCount {
continent: string;
population: number;
}
export const getAnimals = async (
zebraInCountry: ZebraInCountry[],
countriesByArea: CountriesContinent[]
): Promise<ContinentCount[] | null> => {
return countriesByArea.map((obj: CountriesContinent) => {
const { continent, countries } = obj;
return zebraInCountry
.filter(obj => countries.includes(obj.countryName))
.reduce((acc, cur) => {
const population = acc.population + cur.population;
return { population, continent };
});
});
};
const zebraInCountry = [
{ countryName: "Nigeria", population: 100 },
{ countryName: "Ghana", population: 200 },
{ countryName: "Sudan", population: 300 },
{ countryName: "North America", population: 400 },
{ countryName: "South America", population: 100 }
];
const countriesByArea = [
{ continent: "Africa", countries: ["Nigeria", "Ghana", "Sudan"] },
{ continent: "America", countries: ["North America", "South America"] }
];
const zebraPerArea = getAnimals(zebraInCountry, countriesByArea);
console.log(zebraPerArea);

我得到的错误是在acc和cur的reduce参数上

Argument of type '(acc: ZebraInCountry, cur: ZebraInCountry) => { population: number; continent: string; }' is not assignable to parameter of type '(previousValue: ZebraInCountry, currentValue: ZebraInCountry, currentIndex: number, array: ZebraInCountry[]) => ZebraInCountry'.
Property 'countryName' is missing in type '{ population: number; continent: string; }' but required in type 'ZebraInCountry'.

Reduce接受指定累加器类型的Generic参数。它还接受初始值作为第二个参数。

const { continent, countries } = obj;

return zebraInCountry
.filter(obj => countries.includes(obj.countryName))
.reduce<ContinentCount>((acc, cur) => {
const population = acc.population + cur.population;
return { population, continent };
}, {population: 0, continent});

TS操场

最新更新