我试图在对象的 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/