Line 0: Parsing error: Cannot read property 'map' of undefined
Asked Answered
E

19

159

Currently starting up the server on my client side, the error above is what I have been getting. I am using TypeScript, ReactJS, ESLint. I can't seem to go forward since this error has been haunting me. The GitHub page for ESLint hasn't been of much help either.

This error went up after I had created the useMutation component and exported it in index.ts. Not sure how to get rid of this error.

Below is my package.json
    {
    "name": "tinyhouse_client",
    "version": "0.1.0",
    "private": true,
      "dependencies": {
      "@testing-library/jest-dom": "^4.2.4",
      "@testing-library/react": "^9.3.2",
      "@testing-library/user-event": "^7.1.2",
      "@types/jest": "^24.0.0",
      "@types/node": "^12.0.0",
      "@types/react": "^16.9.35",
      "@types/react-dom": "^16.9.0",
      "@typescript-eslint/parser": "^3.0.2",
      "react": "^16.13.1",
      "react-dom": "^16.13.1",
      "react-scripts": "3.4.1",
      "typescript": "~2.23.0"
      },
      "resolutions": {
     "@typescript-eslint/eslint-plugin": "^2.23.0",
     "@typescript-eslint/parser": "^2.23.0",
     "@typescript-eslint/typescript-estree": "^2.23.0"
     },
     "scripts": {
     "start": "react-scripts start",
     " build": "react-scripts build",
     "test": "react-scripts test",
     "eject": "react-scripts eject"
     },
     "eslintConfig": {
     "extends": "react-app"
     },
     "browserslist": {
     "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
      "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
     ]
     },
     **strong text** "proxy": "http://localhost:9000"
      }
Below is my index.ts
    export * from './server';
    export * from './useQuery';
    export * from './useMutation';
And my useMutation.ts
    import { useState } from 'react';
    import { server } from './server';

    interface State<TData> {
    data: TData | null;
    loading: boolean; 
    error: boolean;
    }

    type MutationTuple<TData, TVariables> = [
    (variables?: TVariables | undefined) => Promise<void>,
    State<TData>
    ];

    export const useMutation = <TData = any, TVariables = any>(
    query: string
    ): MutationTuple<TData, TVariables> => { 
    const [state, setState] = useState<State<TData>>({
    data: null,
    loading: false,
    error: false,
    })

    const fetch = async (variables?: TVariables) => {
    try {
      setState({ data: null, loading: true, error: false });

      const { data, errors } = await server.fetch<TData, TVariables>({ query, variables });
      if (errors && errors.length) {
        throw new Error(errors[0].message);
      }

      setState({ data, loading: false, error: false });
    } catch (err) {
      setState({ data: null, loading: false, error: true });
      throw console.error(err);
    }
   }

   return [fetch, state];
};
Expostulation answered 29/5, 2020 at 5:48 Comment(2)
github.com/Jonathanh7/tinyhouse_v1, here is the link to my github repo so you can see that errors I have been getting on your Editors.Expostulation
Similar question here: #63826185Governorship
V
18

Is this coming from eslint-typescript? If so, check that your version of typescript is not a dev/nightly build.

Valgus answered 29/5, 2020 at 10:43 Comment(3)
For me this was solved by downgrading typescript to <4.0, removing node_modules and lock file. Something with create-react-app doesn't support ts 4 yet it seems like.Grainger
Not sure if this is the correct answer for all cases. Regardless of versions of tslint or Typescript problem is in wrong types. Check this: myValue: [][] versus myValue: string[][]. Check answers below.Syndetic
I made this the answer since the version I was previously using was a nightly build. Downgrading it to a none nightly build solved my issue.Expostulation
H
110

Edit: as noted by Meng-Yuan Huang, this issue no longer occurs in react-scripts@^4.0.1

This error occurs because react-scripts has a direct dependency on the 2.xx range of @typescript-eslint/parser and @typescript-eslint/eslint-plugin.

You can fix this by adding a resolutions field to your package.json as follows:

"resolutions": {
  "**/@typescript-eslint/eslint-plugin": "^4.1.1",
  "**/@typescript-eslint/parser": "^4.1.1"
}

NPM users: add the resolutions field above to your package.json but use npx npm-force-resolutions to update package versions in package-lock.json.

Yarn users: you don't need to do anything else. See selective dependency resolutions for more info.

NOTE: if you're using a monorepo/Yarn workspaces, the resolutions field must be in the top-level package.json.

NOTE: yarn add and yarn upgrade-interactive don't respect the resolutions field and they can generate a yarn.lock file with incorrect versions as a result. Watch out.

Hatter answered 16/9, 2020 at 11:46 Comment(3)
see also github.com/typescript-eslint/typescript-eslint/issues/…Hexapody
Thank you! I also had the problem that my returned tuple type [string, string] gave the error Cannot read property 'map' of undefined. This unhelpful message drove me crazy until I found this.Ecclesia
Thanks for your information. However, I fix this problem by updating react-scripts from 3.4.4 to 4.0.1.Molloy
U
95

Your version of TypeScript is not compatible with your eslint. You can fix it by upgrading these two dependencies to the latest version.

TypeScript 4.0.5 is compatible with version 4.6.0

"devDependencies": {
  "@typescript-eslint/eslint-plugin": "^4.6.0",
  "@typescript-eslint/parser": "^4.6.0",
}

TypeScript 4.1.5 is compatible with version 4.18.0

"devDependencies": {
  "@typescript-eslint/eslint-plugin": "^4.18.0",
  "@typescript-eslint/parser": "^4.18.0",
}

TypeScript 4.2.4 is compatible with version 4.23.0

"devDependencies": {
  "@typescript-eslint/eslint-plugin": "^4.23.0",
  "@typescript-eslint/parser": "^4.23.0",
}

TypeScript 4.3.2 is compatible with version 4.25.0

"devDependencies": {
  "@typescript-eslint/eslint-plugin": "^4.25.0",
  "@typescript-eslint/parser": "^4.25.0",
}

TypeScript 4.5.5 is compatible with version 5.10.2

"devDependencies": {
  "@typescript-eslint/eslint-plugin": "^5.10.2",
  "@typescript-eslint/parser": "^5.10.2",
}

TypeScript 4.6.2 is compatible with version 5.15.0

"devDependencies": {
  "@typescript-eslint/eslint-plugin": "^5.15.0",
  "@typescript-eslint/parser": "^5.15.0",
}

TypeScript 4.7.2 is compatible with version 5.26.0

"devDependencies": {
  "@typescript-eslint/eslint-plugin": "^5.26.0",
  "@typescript-eslint/parser": "^5.26.0",
}

TypeScript 4.9.5 is compatible with version 5.56.0

"devDependencies": {
  "@typescript-eslint/eslint-plugin": "^5.56.0",
  "@typescript-eslint/parser": "^5.56.0",
}
Unduly answered 31/10, 2020 at 21:31 Comment(3)
I could not find a resource describing the correct versions to use. In case you have one, it would be great to add the link.Bedazzle
I update my dependencies and when I see it working then I update this answerUnduly
For me did not fixed my issue, but I am aware that is definitely something related with conflict with versions between Typescript and eslintUnderwent
B
74

For future Googlers:

I had the same issue just now on TypeScript 4.0.2 in a Vue.js 2 project. I fixed it by upgrading @typescript-eslint/eslint-plugin and @typescript-eslint/parser to the latest that npm would give me using @latest, which at the time was 3.3.0 and 3.10.1, respectively.

Brougham answered 29/8, 2020 at 22:28 Comment(9)
Although this won't work if you are using an unejected Create React App bootstrapped project.Submaxillary
Hi @JohannesKlauß ! were you able to find out how could you solve this issue with an unejected Create React App project? I am still getting this error. Thanks!Epilate
Haven't checked yet, but you should be able to force a single version via the resolutions field inside the package.json classic.yarnpkg.com/en/docs/selective-version-resolutionsSubmaxillary
Hi again @JohannesKlauß thank you for your response! I finally changed my typescript version to 3.9.5 and the error stopped.Epilate
You can also subscribe to this issue here to track the progress: github.com/facebook/create-react-app/issues/9515Submaxillary
@JohannesKlauß Thanks for the tip, it seems that yarn resolutions don't do any justice either. It's still throwing an error, even by specifying @typescript-eslint/eslint-plugin and @typescript-eslint/parser to 4.0.1. Had to revert back to 3.9.7 and delete the .cache folder as others said.Coit
I think every version < 4 should work. The vital part is the fresh install, so no cache is used.Submaxillary
@JohannesKlauß I also had to revert to 3.9.7 and delete my node_modules directory.Elderly
github.com/typescript-eslint/typescript-eslint/issues/… This helps me to fix this issue. Thanks.Bellbella
E
56

Try playing around with variable types inside the interfaces. E. g I've got this error when I had such state interface:

interface State{
    foo: []
}

but when I've changed the type of array it worked:

interface State{
    foo: string[]
}
Electra answered 30/8, 2020 at 17:50 Comment(5)
This fixes the bug because [] is parsed as a tuple type, while string[] is pared as an array type. In TS 4.0 a property was renamed on the tuple type node in the AST that breaks this. So a possible quick way around the error is to just avoid tuple types if able...Derringdo
@DavidSherret's comment and this answer were what worked for me. Updating the eslint-plugin and parser had no affect. But, reworking the type definition resolve the issue.Hylotheism
Extremely useful, this fixed my issues!Phenetidine
Also replacing [number, number] with number[] as well as other types fixes the remaining errors.Phenetidine
very helpful, I had similar issue, where I declared an array without specifying the type.Copolymerize
L
28

This is what worked for my CRA project.

Step 1: edit package.json and set typescript version to ^3.9.7

Step 2: delete .cache folder in node_modules

Step 3: run npm install

Leanneleanor answered 3/9, 2020 at 20:27 Comment(3)
It fixed after deleting the .cache folderSplenetic
This helped, but I ran into issues with Babel after too, so deleting the whole node_modules directory solved both.Clientele
I also had to remove the entire node_modules directory for this to workMurray
T
21

Sometimes this error is a result of an invalid type as others have stated

I've gotten this error when using a bare array as a type

const someVariable: [] //Incorrect
const someVariable: string[] //Correct

I also got this error when typing an multidimensional array incorrectly:

const someVariable : [string[]] //Incorrect. Results in map error

const someVariable : string[][] //Correct

The error message from typescript is pretty cryptic so hopefully this helps.

Tatiana answered 23/10, 2020 at 17:53 Comment(0)
V
18

Is this coming from eslint-typescript? If so, check that your version of typescript is not a dev/nightly build.

Valgus answered 29/5, 2020 at 10:43 Comment(3)
For me this was solved by downgrading typescript to <4.0, removing node_modules and lock file. Something with create-react-app doesn't support ts 4 yet it seems like.Grainger
Not sure if this is the correct answer for all cases. Regardless of versions of tslint or Typescript problem is in wrong types. Check this: myValue: [][] versus myValue: string[][]. Check answers below.Syndetic
I made this the answer since the version I was previously using was a nightly build. Downgrading it to a none nightly build solved my issue.Expostulation
B
15

I had this same error but the fix for me was that I had one of the type as

text : string[] | []

and changing it to

text : string[]

worked for me

Builtup answered 1/10, 2020 at 11:58 Comment(0)
B
6

Also except array types problems describing im answers above, there are many tuple cases cause this problem.. Let me mention them

interface Some {
  // error
  tupleValue: [string, number]

  // works
  tupleValue: [v1: string, v2: number]

  // error
  tupleArr: [v1: string, v2: number][] 

  // works!
  tupleArr2: Array<[v1: string, v2: number]>
}

another case:

type ValueView = [value: SomeObj, view: string]

// error
const res1: ValueView[] = arr.map(v => [v, v.name])
// works !!!
const res: ValueView[] = arr.map(v => [v, v.name] as ValueView)

// error
const res = arr.map(v => [v, v.name] as [SomeObj, string])
// works !!!
const res = arr.map(v => [v, v.name] as [value: SomeObj, view: string])

So check your tuple operations twice

Bricabrac answered 2/1, 2021 at 14:33 Comment(0)
P
3

for all the guys who is using create-react-app and typescript.

when you encounting some Error like this

upgrade typescript

and

upgrade react-script package

Postman answered 21/1, 2021 at 9:55 Comment(0)
S
3

In case you have dynamically typed function arguments, and Typescript v4 and up, this error may occur. I had

{
  ...
    getDataThunk: (...args: [string]) => dispatch(getData(...args))
  ...
}

This error had never been thrown till I was using TS version <= 4.0.0. Also, Having spread arguments was quite an over-engineering for me, replacing it with exact comma separated function arguments resolved the said issue.

Sealey answered 3/11, 2021 at 7:29 Comment(0)
E
2

I was found this problem and I solve it with change value type in the file

in my case I was declare a

let data: [] = [];

and all of my file is error show Parsing error: Cannot read property 'map' of undefined when I change to

let data: any = [];

It's was work and error was solved.

Erlking answered 10/12, 2021 at 15:24 Comment(0)
P
1

Yarn users, I had the same problem in react, I solved the problem by removing the package-lock.json file and installing again:

rm -rf node_modules
yarn cache clean
yarn install

I'd made with vscode closed by linux terminal, to don't have problem with cache.

Pulcheria answered 1/12, 2020 at 13:23 Comment(1)
If you remove package.json, yarn install won't do anything.Adah
T
1

Had to add the dependencies manually, even when it gave a warning of incompatibility, because the npm-force-resolutions solution did not work for me.

  1. First, I had to add the following dependencies to package.json (dependencies because I'm using create-react-app, which I have never seen to use devDependencies):
"dependencies": {
  "@typescript-eslint/eslint-plugin": "^4.1.1",
  "@typescript-eslint/parser": "^4.1.1",
}
  1. Then, I do rm -rf node_modules/ so I can have a clean install of npm stuff.

  2. Next, install everything: npm install.

  3. Check that you have the correct version: npm ls @typescript-eslint/eslint-plugin. It said UNMET PEER DEPENDENCY but I had to ignore it because otherwise I could not get this working.

  4. npm start to make sure the create-react-app now works.

I'd advice going for the npm-force-resolutions solution first, but if it fails try this one.

Oh, and one extra note:

This entire disaster was because I did something like this:

interface SomeInterface {
  someBoolean: boolean,
  someList: number[],
  someTuple: [string, string]  // <-- THIS is the problem
}

If I removed that commented line, the code would compile without issues. I kept it that way because I had already made my code to work like that, but if you just avoid having a tuple inside the interface (didn't matter if it had labels or not), you can potentially avoid all this hassle.

Tham answered 11/12, 2020 at 16:47 Comment(1)
no need to avoid use tuples, just write someTuple: [v1: string, v2: string] to make it workBricabrac
P
1

I had a property in the react.props interface lie this

someName: [];

changing it to

someName: any[];

fixed the issue

Pinette answered 20/1, 2023 at 16:12 Comment(0)
D
0

You can fix this in your package.json as follows:

"@typescript-eslint/eslint-plugin": "^4.18.0",
"@typescript-eslint/parser": "^4.18.0",

and my typescript version is: "typescript": "^4.1.5"

Diagonal answered 22/9, 2021 at 7:34 Comment(0)
B
0

In my case I had to add two dependencies to "resolutions" in my package.json.

"resolutions": {
    "@typescript-eslint/parser": "^3.0.0",
    "@typescript-eslint/eslint-plugin": "^3.0.0"
}

And I'm using Typescript 4.1.0

Babyblueeyes answered 23/11, 2021 at 19:7 Comment(0)
O
0

The issue I was facing was that I tried to export a type with an a property that was an interface.

After looking one by one, I found that I was using an interface inside a type. So I had to change it back to an interface and the problem was solved

Owain answered 30/9, 2022 at 20:25 Comment(0)
H
0

Updating eslint, plugin and the parser worked for me

npm i eslint@latest @typescript-eslint/eslint-plugin@latest @typescript-eslint/parser@latest
Hofstetter answered 13/10, 2023 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.