1

In Javascript, it is possible to flatten an array of arrays with Array​.prototype​.flat() (you can test it in Chrome's developer console) :

const a = [1, 2, 3]
const b = [4, 5, 6]
const arr = [a, b]
console.log(arr.flat())

Output :

[1, 2, 3, 4, 5, 6]

Now, if I try the same code in TypeScript, I get the following error :

TS2339: Property 'flat' does not exist on type 'number[][]'.

Why ? Is it simply not included in TypeScript ? It does not seem to be a recent nor non-standard feature. Is there another way to call this function ?

There are other ways to flatten arrays of arrays but I find them hardly readable.

Arnaud Denoyelle
  • 25,847
  • 10
  • 73
  • 128
  • this will help https://stackoverflow.com/questions/53556409/typescript-flatmap-flat-flatten-doesnt-exist-on-type-any – Madhawa Priyashantha May 29 '19 at 16:13
  • 1
    That's in ES2019, isn't it? Your `--lib` in [tsconfig](https://www.typescriptlang.org/docs/handbook/compiler-options.html) needs to include [the right library](https://github.com/Microsoft/TypeScript/blob/v3.4.5/lib/lib.es2019.array.d.ts#L39-L133) – jcalz May 29 '19 at 16:13
  • @MadhawaPriyashantha Will the generated code still be compatible with odl browsers or do I need a polyfill ? – Arnaud Denoyelle May 29 '19 at 16:15
  • Definitely works :) I mark my own question as a duplicate of the suggested one. – Arnaud Denoyelle May 29 '19 at 16:20

0 Answers0