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

3
  • 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 }[] Commented Dec 11, 2022 at 0:09
  • @Jayce444 sorry, I should've specified how the object looks. I have updated my post to show it Commented Dec 11, 2022 at 0: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 Commented Dec 11, 2022 at 0:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.