Issue
import React from "react";
import SingleEvent from "./SingleEvent";
interface Item {
id: string;
title: string;
description: string;
location: string;
date: string;
image: string;
isFeatured: false;
}
export default function EventList({ items }) {
return (
<ul>
{items.map((item: Item) => (
<SingleEvent key={item.id} />
))}
</ul>
);
}
I have this component. Here I destructure the props and get the items array. I do want to define the type of that array.
I tried this
function EventList({ items :Item[]})
But this seems not working and also the items props can be an empty array as well.
How do I achieve this using TS?
Solution
When you receive an object as an argument in a function, writing the type information becomes a bit tricky.
You would have to do it like this.
export default function EventList({ items }: { items: Item[] }) {
This makes the code long and repeating, so I personally recommend making a new interface for the props.
interface Props {
items: Item[]
}
export default function EventList({ items }: Props) {
The reason your original code didn't work was because a colon inside Javascript destructuring means renaming that variable. That is why Typescript didn't recognize it as type information.
Answered By - S. J. Hoon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.