I have a groupBy
function in Typescript that is responsible to group array objects by a key from every array:
export const groupBy = <T, K extends string>(array: T[], key: K): Record<K, T> => {
return array.reduce((acc, item) => {
if (!acc[key]) {
acc[key] = []
}
acc[key].push(item)
return acc
}, {} as Record<K, T[]>)
}
const arr = [{name: "Car"}, {name: 'Color'}, {name: 'Car'}]
interface Data {
name: string
}
const res = groupBy<Data[], 'Car' | 'Color'>(arr, 'name')
console.log(res)
What i want to achive is next:
- To be able to add the array type
- To be able to add the keys as
union type - To get the code suggestion when i will consume the result
I added all types for that but i still get a TS error here (const res = groupBy<Data[], ‘Car’ | ‘Color’>(arr, ‘name’)
):
Argument of type '{ name: string; }[]' is not assignable to parameter of type 'Data[][]'.
Type '{ name: string; }' is missing the following properties from type 'Data[]': length, pop, push, concat, and 26 more.(2345)
const arr: {
name: string;
}[]
How to fix the types to not get any errors?