Type 'string' cannot be used to index type 'T'.ts(2536)

Viewed 4436

I'm getting the above error on result[key] in

type DataType = Record<string, number>
export function getDifference<T extends DataType>(data1: T, data2: T): T {
  const keys = Object.keys(data1)
  return keys.reduce<T>((result, key) => {
    result[key] = data1[key] - data2[key]
    return result
  }, {})
}

How do I get rid of it while still returning an generic type T so that the consuming functions still receive the correct type (instead of simply changing T to DataType).

1 Answers

You need to set the correct type for keys as well as result[key] and {} manually since typescript is not able to correctly identify them automatically.

type DataType = Record<string, number>
export function getDifference<T extends DataType>(data1: T, data2: T): T {
  const keys: (keyof T)[] = Object.keys(data1)
  return keys.reduce<T>((result, key) => {
    if(typeof data1[key] === "number" && typeof data2[key]) { // Safeguard against object, array, etc. properties
        result[key] = data1[key] - data2[key] as T[keyof T]
    }
    return result
  }, {} as T)
}
``
Related