TypeScript报错:getServerSideProps取slug提示ParsedUrlQuery类型不存在如何解决
解决方法
报错根因:GetServerSideProps默认未指定动态参数类型,context.params的默认类型为ParsedUrlQuery | undefined,不存在默认的slug属性定义,因此触发TypeScript校验错误。
以下是两种实现方案,优先推荐类型安全的泛型方案:
方案1:泛型指定参数类型(推荐)
给GetServerSideProps传入第二个泛型参数,明确声明你的动态路由参数结构,同时增加非空判断处理边界场景:
import type { GetServerSideProps } from 'next' // 声明当前页面的动态路由参数类型 interface PageRouteParams { slug: string } // 给GetServerSideProps传入泛型:第一个为返回props的类型,第二个为params的类型 export const getServerSideProps: GetServerSideProps<{}, PageRouteParams> = async (context) => { // 边界校验:不存在slug时返回404 if (!context.params?.slug) { return { notFound: true } } // 此处slug已经被TypeScript自动推导为string类型,可直接使用 const slug = context.params.slug return { props: {} } }
方案2:类型断言(快速适配)
如果不需要严格的类型校验,也可以直接通过类型断言指定params的结构:
export const getServerSideProps: GetServerSideProps = async (context) => { const { slug } = context.params as { slug: string } return { props: {} } }
注意:如果你的页面使用可选 catch-all 路由(文件名为
[[...slug]].tsx),需要将slug的类型定义为string | undefined,同时增加额外的空值处理逻辑。
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

