我试图破坏一个数组,但出现以下错误:
Type 'undefined' must have a 'Symbol.iterator' method that returns an iterator.
let [alias, config]: [string, DBConfig] | undefined = Object.entries(info).find(...)
这就是find
定义所显示的内容,它与我定义的相同。
(method) Array<[string, DBConfig]>.find(predicate: (
value: [string, DBConfig],
index: number,
obj: [string, DBConfig][]) => boolean, thisArg?: any
): [string, DBConfig] | undefined (+1 overload)
如果我删除我的定义,它看起来像这样:
let [alias, config] = Object.entries(info).find(...)
然后我得到了同样的错误。我可以做什么(不使用 any
)来使其正常工作?
最佳答案
整个问题归结为这样一个事实:您尝试对可能无法解构的内容(例如 undefined
)使用解构。
如果您确定let [alias, config] = Object.entries(info).find(...)
将永远导致未定义
在你的用例中,那么你只需要转换它:
let [alias, config] = Object.entries(info).find(/*...*/) as [string | DBConfig];
如果它可能导致未定义
,那么您将必须接受可为空的 DBConfig
let [alias, config] = Object.entries(info).find(/*...*/) || ["", null];
关于javascript - 带有数组解构函数的 'Array.prototype.find()' 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55384170/