简体   繁体   中英

NextJS type error while passing props to children

I have a type file with these types:

type IServiceItems = {
  fields: {
    name: string;
    description: string;
    logo: {
      fields: {
        file: {
          url: string;
        };
      };
    };
  };
};

type ITechItems = {
  fields: {
    name: string;
    logo: {
      fields: {
        file: {
          url: string;
        };
      };
    };
  };
};

I have a page where I am fetching data with SSR props. I am trying to pass these props to children. But I am getting type error.

The page tsx file:

interface Props {
  services: IServiceItems[];
  technologies: ITechItems[];
}

const Index = ({ services, technologies }: Props) => {
  return (
    <div>
      <ServicesBlock services={...services} />
      <TechnologiesBlock technologies={...technologies} />
    </div>
  );
};

The error on services and technologies properties:

(property) services: IServiceItems[]
Type '{ services: IServiceItems[]; }' is not assignable to type 'IntrinsicAttributes & IServiceItems[]'.
  Property 'services' does not exist on type 'IntrinsicAttributes & IServiceItems[]'.

And finally the component:

const ServicesBlock = (services: IServiceItems[]) => {}

I tried to use ... when passing the params but did not help.

The data fetch:

export const getServerSideProps = async () => {
  const services = await contentful.getEntries({ content_type: 'service' });
  const technologies = await contentful.getEntries({ content_type: 'technology' });

  return {
    props: {
      services: services.items,
      technologies: technologies.items,
    },
  };
};

You shouldn't spread your services array when passing it as a prop if you are expecting an array (remove the ... ):

const Index = ({ services, technologies }: Props) => {
  return (
    <div>
      <ServicesBlock services={services} />
      <TechnologiesBlock technologies={technologies} />
    </div>
  );
};

Also, change your ServicesBlock declaration as:

interface Props {
    services: IServiceItems[];
}

const ServicesBlock = ({ services }: Props) => {}

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