【问题标题】:Lodash with typescript find not working with overload带有打字稿的Lodash发现不适用于重载
【发布时间】:2020-02-08 01:28:30
【问题描述】:

我正在尝试在对象的打字稿上使用 _.find 来返回该对象的值。 它最初看起来像这样:

  const iconDict = {
    dashboard: <DataVisualizer />,
    settings: <SettingsApp />,
    'company-manager': <CompanyManager />,
    'tenant-administrator': <TenantAdministrator />,
    glob
  const icon =
    _.find(iconDict, (icon, key) => {
      const url = window.location.href
      if (url.indexOf(key) !== -1) {
        return icon
      }
    }) || iconDict['global']

上面的代码给了我错误:

没有重载匹配此调用。 最后一个重载给出了以下错误。 '(icon: Element, key: string) => Element | 类型的参数undefined' 不能分配给“string |”类型的参数号码 |符号 | [字符串 |号码 |符号,任意] |对象迭代器 |部分浅 |不明确的'。 键入'(图标:元素,键:字符串)=> 元素 | undefined' 不可分配给类型 'ObjectIterator'。 输入'元素 | undefined' 不能分配给类型 'boolean'。 类型“未定义”不可分配给类型“布尔”

可能是因为它落在this overload

我尝试像这样添加对象的类型

  const icon =
    _.find<typeof iconDict, JSX.Element>(iconDict, (icon, key) => {
      const url = window.location.href
      if (url.indexOf(key) !== -1) {
        return icon
      }

然后我得到:

类型参数 '(icon: Element, key: string) => Element | undefined' 不可分配给“ObjectIteratorTypeGuard”类型的参数。 签名'(图标:元素,键:字符串):元素 | undefined' 必须是类型谓词.ts(2345)

因为它落在this definition

现在我不确定如何进行。 如何让打字稿知道我将返回对象的值的类型或未定义的类型?

谢谢

【问题讨论】:

    标签: javascript typescript lodash


    【解决方案1】:

    我不确定你是否使用@types/lodash,但这是第一步,给TS一些find的签名。

    有这个 find 的覆盖:

    find<T>(
      collection: List<T> | null | undefined,
      predicate?: ListIterateeCustom<T, boolean>,
      fromIndex?: number
    ): T|undefined;
    

    如果您将谓词更改为

    ,这应该可以工作
    (icon, key) => {
      const url = window.location.href
      return url.indexOf(key) !== -1 ? icon : false
    }
    

    所以它会在未找到的情况下返回boolean

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2021-03-20
      • 2018-02-11
      • 2017-10-25
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多