javascript - Lodash 与 typescript find 不适用于重载

标签 javascript typescript lodash

我试图在对象的 typescript 上使用 _.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']

上面的代码给了我错误:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(icon: Element, key: string) => Element | undefined' is not assignable to parameter of type 'string | number | symbol | [string | number | symbol, any] | ObjectIterator | PartialShallow | undefined'.
      Type '(icon: Element, key: string) => Element | undefined' is not assignable to type 'ObjectIterator'.
        Type 'Element | undefined' is not assignable to type 'boolean'.
          Type 'undefined' is not assignable to type 'boolean'

Probably because it is falling on this overload

I tried to add the typing of the object like this

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

然后我得到:

Argument of type '(icon: Element, key: string) => Element | undefined' is not assignable to parameter of type 'ObjectIteratorTypeGuard'.
  Signature '(icon: Element, key: string): Element | undefined' must be a type predicate.ts(2345)

因为它落在 this definition

现在我不知道如何继续。 如何让 typescript 知道我将返回对象值的类型或未定义的类型?

谢谢

最佳答案

我不确定您是否使用@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

关于javascript - Lodash 与 typescript find 不适用于重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58325667/

相关文章:

javascript - 选择一组三个 li 并将它们显示在下一个或上一个按钮上

javascript - 在 Android 的 WebView 中加载元素时隐藏该元素(或完全阻止其加载)

node.js - 在 typescript 中使用 mysql 类型

javascript - 在lodash中我怎样才能深度删除?

javascript - 使用 JS 从页面属性中通过 AuthorId 获取作者姓名

javascript - async/await 不适用于 promisify

angular - 在 ionic 3 中仅获取格式为 2018-02-28 的日期

javascript - Canvas 绘图 : Await for images to load in a recursive method

javascript - 根据第二个数组中的值过滤对象数组

javascript - 使用 lodash 过滤对象数组中的对象