简体   繁体   中英

How can I fix this Typescript error "Property XXX does not exist..."

I've tried different ways of fixing for this issue but can't do it successfully.

I have the following Reactjs component:

import EventItem from "../EventItem";

type Props = {
  events: [id: number, attributes: { slug: string; name: string; }];
};

const EventList = ({ events }: Props) => {    
  return (
    <section>
      <div className="max-w-7xl mx-auto px-4 mb-5">
        <div className="max-w-sm mx-auto md:max-w-none bg-events-list p-4" data-aos="fade-up">
          <div className="grid gap-12 md:grid-cols-4 md:gap-x-4 md:gap-y-8 items-start">
            {events?.map((eventMap, index) => (
              <EventItem
                key={index}
                url={`/e/${eventMap.attributes.slug}`}
                name={eventMap.attributes.name}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
};

export default EventList;

Typescript warns that

Property 'attributes' does not exist on type 'number | { slug: string; name: string; }'.
  Property 'attributes' does not exist on type 'number'.

And my data structure is:

{
    "id": 2,
    "attributes": {
        "name": "Event Name",
        "slug": "event-name",
    }
}

How can I fix it? What's wrong with my type Props? Thank you!

type Props = {
  events: [id: number, attributes: { slug: string; name: string; }];
};

Your typing said, events is equals to an array with an id, and an object who contains { slug: string; name: string; } { slug: string; name: string; }

But to achieve what you want you must type like this

type Props = {
  events: Array<{id: number, attributes: { slug: string; name: string; }}>;
};

Now, events is an array of objects with your structure:)

Try the following:

type Props = {
  events: { id: number, attributes: { slug: string; name: string; } } [];
};

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