Typescript array of objects as props

Viewed 2777
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?

4 Answers

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.

You need to define the props, and then your destructured variables will infer the type from their object.

So basically, your props can look like this

type EventListProps = {
  items: Item[]
}

and then your component would be:

function EventList(props: EventListProps)

which you can also write as

function EventList({items}: EventListProps)

You can try with any as the particular object named items does not exist in your interface. Also no need to loop object. Try this this works.

export default function EventList({ item }: any) {
  return (
    <ul>
        <SingleEvent key={item.id} />
    </ul>
  );
}
Related