1

I am trying to figure out why my code is telling me that my mapped data that has a property of 'name' is of type never. I am already declaring the commentsData in the interface but there is obviously an error occuring there.

Please see my code below:

interface IProps {
  commentsData: [] 
}

const CommentList: React.FC<IProps> = ({ commentsData }: IProps) => {
  return (
    <div>
      {commentsData.map(comment => {
        return (
          <div>
            {comment.name}
          </div>
        )
      })}
    </div>
  )
}

export const getStaticProps = async ()=> {
  const data = await fetch('https://jsonplaceholder.typicode.com/comments')
    .then((res) => res.json())
    .then((data) => data);
    return {
      props: {
        commentsData: data
      }
    }
}

export default CommentList;

And here is the image with the error that Typescript is throwing: enter image description here

Anyone here ever saw this error? And how did you solve it. Thanks for any help!

enter image description here

Kimbo
  • 191
  • 1
  • 10
  • 2
    Well you didn't specify what `commentsData` is an array **of**. Looks like it's an array of object, so you need to tell Typescript what those objects look like in your interface, e.g. `commentsData: { name: string }[]` – Jayce444 Dec 11 '22 at 00:09
  • @Jayce444 sorry, I should've specified how the object looks. I have updated my post to show it – Kimbo Dec 11 '22 at 00:14
  • 2
    Ok well check gr33nTHumB's answer below, you have to tell Typescript how the object will look when you're defining it in the interface; then when you map over it in the component, it will know the properties the object has. Will fix your typing issue – Jayce444 Dec 11 '22 at 00:38

2 Answers2

2

You need to specify what the array is of. Something like:

interface IComment {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
}

interface IProps {
  commentsData: IComment[] 
}

This way, TypeScript knows what kind of object to expect inside the array.

gr33nTHumB
  • 368
  • 2
  • 9
0

Well, you have to define an interface with an indexer. because it's look like an array of objects.

I am sharing the link which can help you. How can i define an interface for array of an object