Home > Back-end >  Typescript array of objects as props
Typescript array of objects as props

Time:10-05

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?

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

You should try using Array<T>, here is an example, it works also with an empty array []

https://codesandbox.io/s/distracted-neumann-3hyux

CodePudding user response:

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