james emanon
james emanon

Reputation: 11837

Typescript issue with Next.js and getStaticProps

I'm having an issue "typing" this implementation of getStaticProps.

As you notice the result can either return a null data return or something.

So, because of the typings in the getStaticProps, this is also getting messed up. I tried conditional props, but not working for me, any ideas?

type ProductType = {
     props:
         | {
             product: null;
             page: string,
             status: number
          }
        | {
            product: Product;
          }
 }



function ProductPage(props: ProductType): Children  {
  const { product, status, page } = props; // errors here
  if (!product) {
    return (
      <ErrorPage statusCode={status} page={page}  />
    )
  }

  return (
    <ProductPage { ...props } />
  )
}


export default ProductPage;



interface StaticParams extends ParsedUrlQuery {
  id: string
}

type StaticProps = {
  props: {
      product: ProductType;
    }
}
// I get a very long error message here "StaticProps".
// Its like I can't do either "error" values or valid values.
export const getStaticProps: GetStaticProps<StaticProps, StaticParams> = async (context) => {
  const params = context.params!

  const response = await fetch(`${process.env.NEXT_PUBLIC_HOST}/products/${params.id}`);
  const product = await response.json();


  if (!product || product.errors) {
    return {
      props: {
        product: null,
        page: 'error page',
        status: 404
      }
    }
  }


  return {
    props: {
      product: { ...product },
    },
    revalidate: 10
  }
}

Upvotes: 0

Views: 1485

Answers (1)

David Huculak
David Huculak

Reputation: 332

I think you confused yourself here by nesting your ProductType type inside your StaticProps type. As it is written, the full definition of your StaticProps type is:

type StaticProps = {
  props: {
    product: {
      props:
        | {
            product: null
            page: string
            status: number
          }
        | {
            product: Product
          }
    }
  }
}

To fix the compiler error, you need to change the first return statement in your getStaticProps function to be assignable to the type of StaticProps:

return {
  props: {
    product: {
      props: {
        product: null,
        page: 'error page',
        status: 404,
      },
    },
  },
}

While that may allow your code to at least compile, I suspect that you should actually change the definition for the StaticProps type. Also, you will need to make sure the response from your /products/{productId} endpoint also conforms to the StaticProps type to avoid runtime TypeErrors which typescript won't be able to save you from.

Upvotes: 1

Related Questions