首页 > 解决方案 > 如何在打字稿中使用 lodash mapValues

问题描述

我有如下代码:

  interface Item {
    hours: number,
    minutes: number,
  }

  interface DataPoint {
    length: number,
    conversation: {
      a: number,
      b: number,
      [key: string]: number,
    }
  }

  interface DecoratedDataPoint {
    length: Item,
    conversation: {
      a: Item,
      b: Item,
      [key: string]: Item,
    }
  }

我有一个像下面这样使用 lodash函数的mapValues函数


  function dataPointItem(val: number, total: number): Item {
    return {
      hours: Math.floor(val/60),
      minutes: val%60,
      percentage: Math.round((val/total)*100),
    }
  }

  function decorateDataPoint(dataPoint: DataPoint, total: number): DecoratedDataPoint {
    return {
      length: dataPointItem(dataPoint.length, number)
      conversation: _.mapValues(dataPoint.conversation, _.partialRight(dataPointItem, total))
    }
  }

我期望实现的是将计算Item值分配给来自类型ab键。conversationDecoratedDataPoint

但是,此代码不起作用,并且出现错误:

  Type 'Dictionary<Item>' is not assignable to type '{ a: Item; b: Item; }'.
    Property ‘a’ is missing in type 'Dictionary<Item>'.

我检查了_.mapValues(....)调用的结果,它返回了符合Item外观的正确结构化对象。

关于这段代码中有什么错误的任何想法?

标签: typescriptlodash

解决方案


推荐阅读