lon*_*nix 26 typescript angular
我想压扁string[][]成string[].
在几十个SO答案给出的建议是:[].concat(...arrays)。
但这给了我这个错误:
“string[]”类型的参数不可分配给“ConcatArray”类型的参数。
属性“切片”的类型不兼容。
类型 '(start?: number | undefined, end?: number | undefined) => string[]' 不能赋值给类型 '(start?: number | undefined, end?: number | undefined) => never[]' .
类型 'string[]' 不能分配给类型 'never[]'。
类型 'string' 不能分配给类型 'never'。
我尝试的另一种方法是:
let foo: string[][] = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]];
let bar = [].concat(...foo);
Run Code Online (Sandbox Code Playgroud)
这给出了类似的错误:
“string[]”类型的参数不可分配给“ConcatArray”类型的参数。
为什么它对除我以外的所有人都有效?
Gho*_*med 35
尝试这个:
const a = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
const result = a.reduce((accumulator, value) => accumulator.concat(value), []);
console.log(result)Run Code Online (Sandbox Code Playgroud)
Kok*_*oko 14
您可以使用 flat()
let foo: string[][] = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]];
let bar = foo.flat()
Run Code Online (Sandbox Code Playgroud)
日志
console.log(bar) // a,b,c,a,b,c,a,b,c
Run Code Online (Sandbox Code Playgroud)
更新
通过将类型更正为 string[],您还可以使用 concat
let foo: string[][] = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]];
let bar : string[] = []
bar = bar.concat(foo[0], foo[1], foo[2])
Run Code Online (Sandbox Code Playgroud)
gun*_*unn 10
这是最简单的选择:
let bar = ([] as string[]).concat(...foo);
Run Code Online (Sandbox Code Playgroud)
就像@Kokodoko 的方法一样,但带有内联类型。
小智 6
.flat() 也会给出类型错误。您可以使用泛型来解决这个问题
let st : string[][] | Array<string> = [['a'] , ['b']]
let bar = [].concat(...st);
console.log(bar)Run Code Online (Sandbox Code Playgroud)
无论哪种方式,你的电话。只要知道你的类型声明是不正确的。
代码
const res = [].concat(...foo);
Run Code Online (Sandbox Code Playgroud)
应该管用。我猜这是 tsconfig 中的错误配置导致了您的错误。确保tsconfig 的数组中至少有es2015(更好) 。要使新作品如 kokodoko 所示,请确保还添加es2018libflatesnext
"lib": [
"es2018",
"dom",
"esnext"
]
Run Code Online (Sandbox Code Playgroud)
我相信你有 strictNullCheck: true
没有上下文类型的空数组([].concat(arg) 中的 [])在 strictNullChecks 下被推断为 never[]。never 不可从任何其他类型分配。
([] as any[]).concat(foo); 应该能解决问题
这是一个通用的解决方案:
function flatten<T>(arr: T[][]): T[] {
return ([] as T[]).concat(...arr);
}
Run Code Online (Sandbox Code Playgroud)
对于更深层嵌套的数组,例如:
[1, 2, 3, [4, [5, [6, [7]]]]]
type NestedArray<T> = Array<NestedArray<T> | T>;
const flatten = <T>(input: NestedArray<T>, acc: T[] = []): T[] => {
return input.reduce((_: T[], current) => {
if (Array.isArray(current)) return flatten(current, acc);
acc.push(current);
return acc;
}, []);
};
Run Code Online (Sandbox Code Playgroud)
用法:
console.log(flatten([1, 2, 3, [4, [5, [6, [7]]]]]));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21728 次 |
| 最近记录: |