Home > other >  ... could be instantiated with a different subtype of constraint 'string | number | symbol'
... could be instantiated with a different subtype of constraint 'string | number | symbol'

Time:07-01

Typescript Playground

I have a function which takes an array of objects and returns an object with the keys of all the objects and their values as an array. (I dont know how to name it though)

it works, but Typescript is deeply unhappy with it. I do not quite understand the error, especially not in this context. Shouldn't the function be able to deal with all subtypes of {}[]? Or is Typescript trying to tell me something different?

The main error:

'string' is assignable to the constraint of type 'K', but 'K' could be instantiated with 
 a different subtype of constraint 'string | number | symbol'.ts(2322)

The code:

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
}

CodePudding user response:

Try this:

function objectsKeysInArrayToObject<
    T extends readonly Record<string, string>[]
>(array: T) {
    const result = array.reduce((acc: Record<string, string[]>, curr: Record<string, string>) => {
        const keyValuePairs = Object.entries(curr)

        for (const [key, value] of keyValuePairs) {
            if (acc[key] === undefined) {
                acc[key] = [value]
            } else {
                acc[key].push(value)
            }
        }
        return acc
    }, {})

    return result
}

TS Playground

It's functionally identical to your code, but circumvents the issue you're encountering by having fewer explicit type declarations (and instead letting TS figure out what the right types ought to be).

  • Related