0

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!

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

Try the following:

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

1 Comment

That worked too! (I guess is the same thing that the other answer but just in a different way). Thank you for your help! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.