Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type the getStaticProps function when using getStaticPaths params?

I working on the following piece of code:

It's a blogPost dynamic page: /post/[slug].tsx

export const getStaticPaths: GetStaticPaths = async () => {
  const allSlugs = await getAllSlugs();;
  return ({
    paths: allSlugs.map((slug) => ({ params: { slug }})),
    fallback: "blocking"
  });
};

export const getStaticProps: GetStaticProps = async (context) => {
  const slug = context.params.slug;
  const blogPost = getBlogPostFromSlug({slug});
  return ({
    props: {
      blogPost
    }
  });
};

This is the error I'm getting:

enter image description here

It seems that the GetStaticProps type is generic and can be customized for my types.

enter image description here

I created those two types to try to customize the GetStaticProps type:

type ContextParams = {
  slug: string
}

type PageProps = {
  blogPost: null | Types.BlogPost.Item
}

Here is what I'm trying:

export const getStaticProps: GetStaticProps<PageProps,ContextParams> = async (context) => {
  const slug = context.params.slug;
  const blogPost = await getBlogPostFromSlug({slug});
  return ({
    props: {
      blogPost
    }
  });
};

But it still thinks that params might be undefined. Should I just deal with it? From the code above, does it seem like params could be undefined? I wasn't expecting that.

like image 617
cbdeveloper Avatar asked Aug 12 '26 00:08

cbdeveloper


1 Answers

The types are defined such that the params variable must still be undefined even when you declare the type for the params Q. From the types file:

export type GetStaticPropsContext<Q extends ParsedUrlQuery = ParsedUrlQuery> = {
  params?: Q
...

So if you want to be safe then you should assume that you might not have params. I would use the notFound or redirect properties explained here to handle requests with with missing params. You also want to handle cases where your async function getBlogPostFromSlug was rejected.

export const getStaticProps: GetStaticProps<PageProps, ContextParams> = async (
  context
) => {
  const slug = context.params?.slug;
  if (slug) {
    try {
      const blogPost = await getBlogPostFromSlug({ slug });
      return {
        props: {
          blogPost
        }
      };
    } catch (error) { }
  }
  return {
    notFound: true
  };
};

Typescript Playground Link

like image 100
Linda Paiste Avatar answered Aug 14 '26 14:08

Linda Paiste



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!