是否可以减少打字稿中具有未知属性名称的通用对象?

问题描述:

是否可以通过对任何通用对象的属性求和来将两个归约对象合二为一

Is it possible to two reduce objects into one by summing their properties like so for any generic object

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

我希望得到一些功能

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

当我尝试这个解决方案时

when I try this solution

function reduceObjectsGeneric<T extends {readonly [key: string]: number}>(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

类型 'string' 不能用于索引类型 '{} &T'.ts(2536)

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

实现这种行为的功能方式是什么?

What is the functional way to implement this behaviour?

函数式方法将是(但可能不干净)

A functional approach would be (but probably not clean)

function reduceObjects<T extends { [key: string]: number }>(a: T, b: T): T {
  return Object.keys(a).reduce(
    (acc, key) => Object.assign(acc, { [key]: a[key] + b[key] }),
    b
  );
}

首先,您获取对象a"的键;使用 Object.keys.然后您使用 JavaScript 的 Array.reduce 方法迭代键并将其分配给键".的acc"对象.

First, you get the keys of object "a" using Object.keys. Then you use the Array.reduce method of JavaScript to iterate over the keys and assign it to the "key" of the "acc" object.