简体   繁体   中英

Typescript array of objects as props

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?

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 should try using Array<T> , here is an example, it works also with an empty array []

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

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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM