是否可以减少打字稿中具有未知属性名称的通用对象? [英] Is it possible to reduce generic objects with unknown property names in typescript?

查看:35
本文介绍了是否可以减少打字稿中具有未知属性名称的通用对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于是否可以减少打字稿中具有未知属性名称的通用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆