You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中使用GetStaticProps时TypeScript解构id报错求助

使用GetStaticProps类型时TypeScript报错的问题

我在给代码中的getStaticProps标注GetStaticProps类型时,TypeScript会报错,但不标注类型时代码运行完全正常,对此我很困惑。

代码示例

interface RowProps {
  id: number;
  created_at: Date;
  title: string;
  description: string;
}

interface PageProps {
  lesson: RowProps;
}

// 我原本定义的参数接口
interface PageParams extends ParsedUrlQuery {
  params: {
    id: string;
  }
}

// 这段代码运行正常(未标注GetStaticProps类型):
// export const getStaticProps = async ({ params: { id } }: PageParams) => {
//   const { data: lesson } = await supabase
//     .from("lesson")
//     .select("*")
//     .eq("id", id)
//     .single();

//   return {
//     props: {
//       lesson,
//     },
//   };
// };

// 这段代码报错(标注了GetStaticProps类型):
export const getStaticProps: GetStaticProps<PageProps, PageParams> = async ({
  params: { id },
}) => {
  const { data: lesson } = await supabase
    .from("lesson")
    .select("*")
    .eq("id", id)
    .single();

  return {
    props: {
      lesson,
    },
  };
};

报错信息

Property 'id' does not exist on type 'PageParams | undefined'.ts(2339)

问题原因及解决方案

1. 参数接口定义错误

你的PageParams结构不符合Next.js的实际参数规范。在Next.js中,getStaticProps的context里的params本身就是动态路由参数的对象(比如对于/lesson/[id],params就是{ id: string }),不需要嵌套一层params属性。正确的PageParams应该这样定义:

interface PageParams extends ParsedUrlQuery {
  id: string;
}

2. params存在可选性

当你标注GetStaticProps类型后,TypeScript会严格遵循Next.js的类型定义——params是可选的(比如在非动态路由页面中,params会是undefined)。而你之前未标注类型时,TypeScript没有强制校验这种可选性,所以没报错。

3. 修复后的代码

结合上面两点,修正后的代码如下:

interface RowProps {
  id: number;
  created_at: Date;
  title: string;
  description: string;
}

interface PageProps {
  lesson: RowProps;
}

// 修正参数接口定义
interface PageParams extends ParsedUrlQuery {
  id: string;
}

export const getStaticProps: GetStaticProps<PageProps, PageParams> = async ({ params }) => {
  // 先检查params是否存在,避免undefined报错
  if (!params) {
    return { notFound: true };
  }

  const { id } = params;
  const { data: lesson } = await supabase
    .from("lesson")
    .select("*")
    .eq("id", id)
    .single();

  return {
    props: {
      lesson,
    },
  };
};

或者你也可以在解构时直接处理可选性,用默认值兜底:

export const getStaticProps: GetStaticProps<PageProps, PageParams> = async ({ params = {} }) => {
  const { id } = params;
  if (!id) {
    return { notFound: true };
  }
  // 后续逻辑...
};

内容的提问来源于stack exchange,提问作者Gary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:05:29