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

Time:04-03

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!

CodePudding user response:

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

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 :)

CodePudding user response:

Try the following:

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

CodePudding user response:

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

It seems that events type should be object but array. Could you try this?

  • Related