How to best handle getStaticProps scenarios with TS?

Viewed 95

Seems like a difficult scenario.

The ctx object has a lot of optional types. Params for example could be an array or a string + null | undefined

A naive approach I used is the below, but it doesn't cover for id to be an array past the type definition in getPostData(id : string | Array).

Is there a better way to approach this?

// /pages/posts/[id].tsx
import { GetStaticProps, GetStaticPaths } from "next";

...

export const getStaticProps: GetStaticProps = async ({ params }) => {
  // params types is not specified above
  // the use of params is making sure that params has an id -- ?
  //      and we also remove undefine type from the union
  const postData = await getPostData(params?.id!);
  return {
    props: {
      postData,
    },
  };
};
0 Answers
Related