Home > Software engineering >  getStaticProps error with Typescript, Next js
getStaticProps error with Typescript, Next js

Time:10-12

So I have this code:

export const getStaticProps: GetStaticProps<HomeProps> = async () => {
    const firstCategory = 0;
    const { data }: AxiosResponse<MenuItem[]> = await axios.post(
        process.env.NEXT_PUBLIC_DOMAIN   '/api/top-page/find',
        {
            firstCategory,
        }
    );
    return {
        props: {
            data,
            firstCategory,
        },
    };
};

interface HomeProps extends Record<string, unknown> {
    menu: MenuItem[];
    firstCategory: number;
}

But I had an error:

Type '() => Promise<{ props: { data: MenuItem[]; firstCategory: number; }; }>' is not assignable to type 'GetStaticProps<HomeProps, ParsedUrlQuery>'.
  Type 'Promise<{ props: { data: MenuItem[]; firstCategory: number; }; }>' is not assignable to type 'GetStaticPropsResult<HomeProps> | Promise<GetStaticPropsResult<HomeProps>>'.
    Type 'Promise<{ props: { data: MenuItem[]; firstCategory: number; }; }>' is not assignable to type 'Promise<GetStaticPropsResult<HomeProps>>'.
      Type '{ props: { data: MenuItem[]; firstCategory: number; }; }' is not assignable to type 'GetStaticPropsResult<HomeProps>'.
        Type '{ props: { data: MenuItem[]; firstCategory: number; }; }' is not assignable to type '{ props: HomeProps; revalidate?: number | boolean | undefined; }'.
          Types of property 'props' are incompatible.
            Property 'menu' is missing in type '{ data: MenuItem[]; firstCategory: number; }' but required in type 'HomeProps'.ts(2322)

And I really don't know what is the ParsedUrlQuery. I tried to import it(import { ParsedUrlQuery } from 'querystring';). But it doesn't help.

What should I do?

CodePudding user response:

HomeProps contains menu: MenuItem[], but then you're trying to return data: MenuItem[]. If the type is correct, then update the code to return this:

return {
  props: {
    menu: data,
    firstCategory,
  },
};

Or if the code is correct but the type is wrong, update the type:

interface HomeProps extends Record<string, unknown> {
    data: MenuItem[];
    firstCategory: number;
}
  • Related