Zod v4解析路径参数总是字符串吗?

前端开发 2026-07-12

我在使用 @tanstack/zod-adapter 来解析路径参数:

export const Route = createFileRoute(
  "/route/$one/$two/$three",
)({
  params: zodValidator(
    z.object({
      one: z.number(),
      two: z.string(),
      three: z.string(),
    }),
  )},
  component: RouteComponent,
});

然而,当使用 <Link /> 组件进行路由时:

<Link
  to="/route/$one/$two/$three"
  params={{
    one: 1234,
    two: "value",
    three: "otherValue",
  }}
>
  {/* ... */}
</Link>

这里的期望结果应该是在路由中是一个数字,但Zod会抛出错误,因为参数是字符串?

解决方案

你试过吗?:

z.coerce.number()

而不是:

z.number()

https://zod.dev/api?id=coercion

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章