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

如何将NextJS router.query.id的类型指定为string?

问题:T3栈中如何优雅处理路由参数的string类型转换

我是TypeScript及T3栈(React Query/Tanstack Query)的新手,希望将companyId指定为string类型,避免每次使用时都写companyId as string,但不清楚该栈下的最佳实践。我习惯用原生JavaScript和useEffect调用API,代码可能不够规范。

注意:以下代码位于/pages/companies/[id].tsx

第一次尝试:触发"Rendered more hooks than during the previous render"错误

const CompanyPage: NextPage = () => {
  const router = useRouter()

  const companyId = router.query.id
  if (!companyId || Array.isArray(companyId)) return <div>Loading...</div> // 必须检查是否为数组,这是NextJS/Typescript的已知问题

  const { data: company } = api.companies.getSingleById.useQuery({companyId: companyId});
  if (!company ) return <div>Loading...</div>

  ...
  return (...)
}

直接指定类型失败

尝试直接给companyId指定string类型,但由于router.query.id的类型是string | string[] | undefined,导致类型报错:

const CompanyPage: NextPage = () => {
  const router = useRouter()

  const companyId: string = router.query.id // 类型“string | string[] | undefined”不能赋值给类型“string”

  const { data: company } = api.companies.getSingleById.useQuery({companyId: companyId});
  if (!company ) return <div>Loading...</div>

  ...
  return (...)
}

更新:可行但不确定是否规范的写法

改成以下代码后能运行,但不确定是否是正确做法(此方法只需写一次companyId as string):

const CompanyPage: NextPage = () => {
  const router = useRouter()

  const companyId = router.query.id
  const { data: company } = api.companies.getSingleById.useQuery({companyId: companyId as string});

  if (!companyId || Array.isArray(companyId)) return <div>Loading...</div> // 必须检查是否为数组,这是NextJS/Typescript的已知问题
  if (!company ) return <div>Loading...</div>

  ...
  return (...)
}

最终解决方案

感谢Fabio的解答,我在多参数路由中采用useMemo解构并转换类型,示例如下:

const { companyId, locationId } = useMemo(() => ({
  companyId: router.query?.companyId?.toString() ?? "",
  locationId: router.query?.locationId?.toString() ?? "",
}), [router.query?.companyId, router.query?.locationId]);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:05:04