0

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

1 Answer 1

1

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.

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

Comments

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.