1

Is it possible to two reduce objects into one by adding their properties like so for any generic object in typescript?

const A = {x:1, y:1, z:1}
const B = {x:2, y:2, z:2}
// result {x:3, y:3, z:3}

I am hoping to get some function

function reduceObjects<T extends {[key: string]: number}>(previousObject:T, currentObject:T) => T

when I try this solution

function reduceObjects<T>(currentValue: T , previousValue: T): T {
  const result = Object.assign({}, previousValue);


  Object.keys(previousValue).forEach((k) => {
    // eslint-disable-next-line functional/immutable-data
    result[k]=previousValue[k]+currentValue[k]
  })

  return result
}

I get the following error in the inner loop

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. No index signature with a parameter of type 'string' was found on type 'unknown'.

0 Answers0