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

avatar
Borislav Hadzhiev

Last updated: Feb 27, 2024
2 min

banner

# 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" ] } }
The code for this article is available on GitHub

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 flatmap in typescript

The code for this article is available on GitHub

Here is an example of using the Array.flat method.

index.ts
// ๐Ÿ‘‡๏ธ using Array.flat const arr = [ ['a', 'b'], ['c', 'd'], ]; // ๐Ÿ‘‡๏ธ const flat: string[] const flat = arr.flat(); // ๐Ÿ‘‡๏ธ ['a', 'b', 'c', 'd'] console.log(flat);

using flat in typescript

# Update your version of typescript

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 use Angular.js, you might have to update your version if the error persists.

# Using 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.

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(' '); }

using replace instead of flatmap

The code for this article is available on GitHub

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.

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.

Copyright ยฉ 2024 Borislav Hadzhiev