If I use a typescript tuple in my react-app i get a eslint error on line 1 in vscode?

All we need is an easy explanation of the problem, so here it is.

The error is Parsing error: Cannot read property 'map' of undefined

I set up a new file just to reproduce the error:

export default () => {
  let something: [string, boolean]
  something = ['something', true];
}

am i missing something? all other types seem to work fine.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The Problem

The problem is when you created the tuple type [string, boolean] this is a new way to declare types with arrays introduced in Typescript 4.0 called Labeled Tuple Types.

The Solution

Upgrade your react-scripts to v4 (Here is the issue on their github). If you are using yarn use the command yarn upgrade [email protected]. With npm should be something similar, you can try npm install [email protected]

Method 2

If i right understand you, here is your solution (you don’t have to create a let in order to register the types, but directly in the function specify which types it will return)

// main.ts
export default (): [string, boolean] => {
 return ["something", true];
};

And if you need to call this code, you just create such a component(example):

import foo from "./main.ts"

const App = () => {
  return (
    <div>
      {foo().map(el =>
        <div>
          {el}
        </div>
      )}
    </div>
  )
};

Method 3

Indeed it appears that the issue is with using the let keyword.
I was experiencing this when converting to TS after using let in just JavaScript a bunch of times without a hitch, but changing to const fixed it down the line.

Here are some intricacies between let and const detailed on the TypeScript website: https://www.typescriptlang.org/docs/handbook/variable-declarations.html#let-vs-const

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply