I developed a function that takes an array of objects and transforms it into an object where the keys represent all the keys from the original objects, paired with arrays of their respective values.
Although the functionality is correct, Typescript raises some issues with the implementation.
I am struggling to comprehend the error message, particularly within this particular context. Shouldn't the function be inherently capable of handling all variants of {}[]
? Or does Typescript intend to convey something different?
The primary error being reported is:
'string' is assigned to 'K', however 'K' could potentially infer a distinct subtype than 'string | number | symbol'.ts(2322)
Here is the code snippet in question:
function objectsKeysInArrayToObject<
T extends readonly {}[],
K extends keyof T[number]
>(array: T): Record<K, T[number][K]> {
const result = array.reduce((acc, curr) => {
const keyValuePairs: [K, T[number][K]][] = Object.entries(curr)
for (const [key, value] of keyValuePairs) {
if (acc[key] == undefined) {
acc[key] = [value]
} else {
acc[key].push(value)
}
}
return acc
}, {} as Record<K, T[number][K]>) as Record<K, T[number][K]>
return result
}