typescript - 如何在 TS 中最佳處理 getStaticProps 情境?
看起來像是一個困難的情況。
ctx 物件有很多可選類型。例如,Params 可以是陣列或字串加上 null | undefined
我使用的一種天真的方法如下,但它無法涵蓋在 getPostData(id : string | Array) 的類型定義之外,id 為陣列的情況。
有沒有更好的方法來處理這個問題?
// /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,
},
};
};