I have an array of Product
.
The Product
class:
class Product {
id: string;
type: string;
price: number;
constructor(id: string, type: string, price: number) {
this.id = id;
this.type = type;
this.price = price;
}
}
I try to group the array of product by its type
property by using the array reduce function:
const groupedProducts = productList.reduce((group, prod) => {
const prodType = prod.type;
group[prodType] = group[prodType] ?? [];
group[prodType].push(prod);
return group;
}, {});
Above code gets compiler error:
No index signature with a parameter of type 'string' was found on type '{}'.
I see that it is because of the initial value {}
has no explicit type for the object index, so I refactored the initial value part from {}
to {string: Product[]}
. But it doesn't help.
The full code is here.
How can I get rid of this error & get the grouped products as a result?
CodePudding user response:
The correct approach would probably be to specify the generic type of reduce
explicitly.
const groupedProducts = productList.reduce<Record<string, Product[]>>((group, prod) => {
const prodType = prod.type;
group[prodType] = group[prodType] ?? [];
group[prodType].push(prod);
return group;
}, {});
This correctly types the group
parameter and the return type as Record<string, Product[]>
.