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:
Anyone here ever saw this error? And how did you solve it. Thanks for any help!
CodePudding user response:
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.
CodePudding user response:
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