0

I'm trying to understand how to add TypeScript to my .map method, but at the moment, I'm getting the following error message. I'm not really sure what the 'never' keyword signifies either.

TS2339: Property 'fname' does not exist on type 'never'

The code I'm using is:

const [climbs, setClimbs] = useState([]);
...
useEffect(() => {
  async function data() {
    try {
      const getClimbs = await axios.get("http://localhost:4000/climbs");
      setClimbs(getClimbs.data);
    } catch (err) {}
  }
  data();
}, []);
...
<div className="list">
  {climbs.map(climb => {
    return (
      <>
        <div className="list-name">{climb.fname}</div>
        <div className="list-recent-climb">
          {climb.climb} - {climb.grade} - {climb.location}
        </div>
        <div className="list-date">{climb.date}</div>
      </>
    );
  })}
</div>
...

I also tried adding a type object at the top to see if that would clear things up. I'm new to TypeScript so trying to get my bearings.

type Props = {
  fname: String,
  climb: String,
  grade: String,
  location: String,
  date: Date
}
pingeyeg
  • 632
  • 2
  • 6
  • 23
  • You should share a bit more code, specifically the parts where `climbs` is created. – Evert Oct 02 '19 at 15:43
  • Updated my question – pingeyeg Oct 02 '19 at 15:46
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Evert Oct 02 '19 at 15:48
  • @Evert How/why are you considering this to be a duplicate. I don't see anywhere on that linked question about TypeScript or the .map array method, which is specific to my question. – pingeyeg Oct 02 '19 at 15:59
  • Sorry, it was still only a partial sample, so I jumped to the conclusion that you were using a variable before it was available. Sorry if that was a wrong assumption – Evert Oct 02 '19 at 16:45

1 Answers1

1

It is because you are calling useState with an empty array which defaults to type never[]. Change it to:

React.useState<Props[]>([])
chautelly
  • 447
  • 3
  • 14
  • Or `React.useState([] as Props[])` – chautelly Oct 02 '19 at 16:20
  • Thank you, that worked. Now I just need to learn why that is. – pingeyeg Oct 02 '19 at 16:22
  • Are familiar with type generics? – chautelly Oct 02 '19 at 16:28
  • I'm not, but just read up on it. It sounds like you are making a generic start so that you can use any kind of type for later. Does that not go against the point of TypeScript? – pingeyeg Oct 02 '19 at 17:22
  • 1
    The compiler can't infer the type of your empty array just by looking in other locations how you might be using . You have to let TypeScript know what they type of your empty array is so that it can properly infer the usage of `useState` – chautelly Oct 02 '19 at 17:58