gpt4 book ai didi

typescript - 在 TypeScript 中展平数组

转载 作者:搜寻专家 更新时间:2023-10-30 22:04:37 28 4
gpt4 key购买 nike

我想将 string[][] 扁平化为 string[]

数十个 SO 答案中给出的建议是:[].concat(...arrays)

但这给了我这个错误:

Argument of type 'string[]' is not assignable to parameter of type 'ConcatArray'.
Types of property 'slice' are incompatible.
Type '(start?: number | undefined, end?: number | undefined) => string[]' is not assignable to type '(start?: number | undefined, end?: number | undefined) => never[]'.
Type 'string[]' is not assignable to type 'never[]'.
Type 'string' is not assignable to type 'never'.

我尝试的另一种方法是:

let foo: string[][] = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]];
let bar = [].concat(...foo);

这给出了类似的错误:

Argument of type 'string[]' is not assignable to parameter of type 'ConcatArray'.

为什么它对除我以外的所有人都有效?

最佳答案

试试这个:

const a = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
const result = a.reduce((accumulator, value) => accumulator.concat(value), []);
console.log(result)

关于typescript - 在 TypeScript 中展平数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56544572/

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