【问题标题】:Lodash Dictionary replacement in ES6ES6 中的 Lodash 字典替换
【发布时间】:2021-06-01 19:05:25
【问题描述】:

我们一直在一个旧的 TypeScript 项目中使用 lodash。现在我们正在迁移到 ES6 模块,所以用 lodash-es 替换 lodash。在 lodash 中声明了一个 Dictionary 类型: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/common/common.d.ts#L247-L249

interface Dictionary<T> {
    [index: string]: T;
}

我们用它来声明一些像这样的字段:

labTransGrouped: Dictionary<Array<ILabtransItem>>;

lodash-es 中没有明显的替换。我想我应该改用 TypeScript Map 之类的东西。但是在我的情况下,在类型声明中使用它的正确方法是什么?我在 lodash 变更日志或迁移指南中找不到任何提及,所以一定很简单。

【问题讨论】:

  • 或者你可以定义自己的Dictionary接口?
  • 你安装了@types/lodash-es 吗?
  • @Terry 确实是的,但这是一个基本概念,我无法想象没有标准的方法可以实现这一点。所以我只是不想发明自行车。
  • @Anatoly 是的,我做到了,用@types/lodash-es 替换了@types/lodash。然后 TypeScript 开始抱怨 Dictionary 的使用。

标签: typescript ecmascript-6 lodash typescript-typings


【解决方案1】:

lodash-es 使用来自lodashDictionary 的定义。

import _ from 'lodash-es';
import { Dictionary } from 'lodash';

interface ILabtransItem {
    a: string;
}

const arr: Dictionary<Array<ILabtransItem>> = {}
const groupedArr = _.groupBy(arr, x => x[0].a)

试试看here
lodash-esheregroupBy的定义

【讨论】:

    【解决方案2】:

    我遇到了同样的问题。

    lodash-es当然没有Dictionary类型,但Dictionary就是这么简单的类型,你甚至不需要自己创建。

    只需在代码中的某处复制 Dictionary 类型并导入。

    export interface Dictionary<T> {
      [index: string]: T;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 2015-12-13
      • 2015-01-24
      • 2021-08-31
      • 1970-01-01
      • 2011-08-05
      • 2016-06-07
      相关资源
      最近更新 更多