Property 'flatMap', 'flat' does not exist on type in TS

avatar

Borislav Hadzhiev

Last updated: Mar 5, 2022

banner

Photo from Unsplash

Property 'flatMap', 'flat' does not exist on type in TS #

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.

tsconfig.json
{ "compilerOptions": { // ... other options "lib": [ // ... other libs "es2019" ] } }

This will resolve the error and you will be able to use the flatMap and flat methods.

index.ts
// 👇️ using Array.flatMap const arr = ['one two', 'three four']; const result = arr.flatMap((str) => str.split(' ')); // 👇️ ['one', 'two', 'three', 'four'] console.log(result); // 👇️ using Array.flat const arr2 = [ ['a', 'b'], ['c', 'd'], ]; // 👇️ const flat: string[] const flat = arr2.flat(); // 👇️ ['a', 'b', 'c', 'd'] console.log(flat);

If you are still unable to use the flatMap method, make sure you're running a recent version of TypeScript.

shell
npm install -g typescript@latest npm install --save-dev typescript@latest
If you are using Angular.js, you might have to update your version if the error persists.

If you are still getting an error, here is an example of how I would rewrite the code snippet above without using flatMap.

index.ts
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 with the result of calling the split() method on a string, which is another array.

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.