typescript

Flatten array of arrays in TypeScript


I want to flatten string[][] into string[].

The advice given in dozens of SO answers is: [].concat(...arrays).

But that gives me this error:

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'.

Another way I tried is this:

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

Which gives a similar error:

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

Why does it work for everyone but me?


Solution

  • Try this:

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