Next.js中传递getServerSideProps类型至页面Props的最佳实践选型
在Next.js开发中,哪种传递getServerSideProps类型至页面Props的方式更规范?
我找到了两种可正常运行的解决方案,但不确定哪种方法更符合规范。
相关代码如下:
接口定义
interface ICatalogHome { response: Result<CatalogHomePageResponse>; }
getServerSideProps实现
export const getServerSideProps: GetServerSideProps<ICatalogHome> = async (context) => { const appSlug = context.params?.appSlug; const { locale } = context; const response = await getCatalogHomePageData(appSlug as string, locale!); const notFound = !response; return { props: { response, ...(await serverSideTranslations(context.locale!, ['common', 'login'])) }, // will be passed to the page component as props notFound }; };
两种页面组件写法
第一种方式:
const CatalogHome: NextPage<InferGetServerSidePropsType<typeof getServerSideProps>> = ({ response }) => {...}
第二种方式:
const CatalogHome = ({ response }: InferGetServerSidePropsType<typeof getServerSideProps>) => {...}
请问在Next.js开发实践中,哪种传递getServerSideProps类型至页面Props的方式更规范?
解答
在Next.js Pages Router的官方实践中,第一种使用NextPage泛型的方式更符合规范,原因如下:
NextPage是Next.js专为页面组件提供的类型,它不仅能通过泛型接收Props类型,还内置了页面组件特有的类型约束(比如关联getInitialProps、页面布局等相关类型),能提供更全面的类型校验。- 这种写法语义更清晰,直接表明这是一个Next.js页面组件,而非普通React函数组件,团队协作时可读性更强。
- 第二种方式仅给组件参数标注了类型,没有关联Next.js页面组件的专属类型,在复杂场景(如使用页面级布局、自定义App中的类型传递)下,可能会缺失部分类型校验能力。
注:如果使用Next.js 13+的App Router,getServerSideProps已被弃用,需改用新的数据获取方案,但在Pages Router体系中,上述规范依然适用。
内容的提问来源于stack exchange,提问作者Sefa Dönmezcan
相关产品推荐
相关产品推荐

