Last updated: Feb 27, 2024
Reading timeยท2 min
To solve the "Property 'flatMap' or 'flat' does not exist on type" error, add
the string "es2019"
to the lib
array in your tsconfig.json
file and make
sure you are running a recent version of TypeScript.
Open your tsconfig.json file and add
es2019
to your lib
array.
{ "compilerOptions": { // ... other options "lib": [ // ... other libs "es2019" ] } }
This will resolve the error and you will be able to use the flatMap and flat methods.
// ๐๏ธ using Array.flatMap const arr = ['one two', 'three four']; const result = arr.flatMap((str) => str.split(' ')); // ๐๏ธ ['one', 'two', 'three', 'four'] console.log(result);
Here is an example of using the Array.flat
method.
// ๐๏ธ using Array.flat const arr = [ ['a', 'b'], ['c', 'd'], ]; // ๐๏ธ const flat: string[] const flat = arr.flat(); // ๐๏ธ ['a', 'b', 'c', 'd'] console.log(flat);
typescript
If you are still unable to use the flatMap
method, make sure you're
running a recent version of TypeScript.
npm install -g typescript@latest npm install --save-dev typescript@latest
replace
instead of flatMap
If you still get an error, here is an example of how I would rewrite the code
sample without using flatMap
.
const arr = ['one two', 'three four']; const result = arr.reduce<string[]>( (acc, curr) => acc.concat(splitOnSpace(curr)), [], ); console.log(result); // ๐๏ธ ['one', 'two', 'three', 'four'] function splitOnSpace(str: string) { return str.split(' '); }
We used the reduce() method and set its return
type and the type of the accumulator
variable to be an array of strings (
string[]
).
On each iteration, we concatenate the accumulated array to the result of calling
the split()
method on a string.
I've also written a detailed guide on how to flatten an array of arrays in TS.