gpt4 book ai didi

typescript - 数组 concat 的返回类型

转载 作者:行者123 更新时间:2023-12-04 13:29:20 25 4
gpt4 key购买 nike

我有一个方法可以从嵌套对象中创建一个扁平对象数组。

{a: 'b',
c: {d: 'e'}
}
将会
[{a: 'b'}, {d:'e'}]
所以这个方法的返回类型是一个对象数组( Record<string, any>[] )。但是 typescript 给出了以下错误:
TS2769:没有与此调用匹配的重载。
...
'Record [] | 类型的参数{ [x: 字符串]: 任何; }' 不能分配给'ConcatArray' 类型的参数。类型 'Record []' 不能分配给类型 'ConcatArray'。
_flatten 的正确返回类型是什么?方法:
const _flatten = (obj: Record<string, any>): Record<string, any>[] =>  
[].concat(...Object.keys(obj)
.map((key: string) => (
typeof obj[key] === 'object' ? _flatten(obj[key]) : { [key]: obj[key] }
))
);

最佳答案

我猜错误信息是这样的:

Type 'Record<string, any>[]' is not assignable to type 'ConcatArray<never>'
那是因为你使用了 [].concat[]never[] 的类型.
尝试使用 Array.prototype.concat反而:
const _flatten = (obj: Record<string, any>): Record<string, any>[] =>  
Array.prototype.concat(...Object.keys(obj)
.map((key: string) => (
typeof obj[key] === 'object' ? _flatten(obj[key]) : { [key]: obj[key] }
))
);
Typescript sandbox
或者您可以输入提示 []像这个:
([] as any[]).concat(/* omitted */)

关于typescript - 数组 concat 的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66028403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com