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

从路由映射生成带参数约束的TypeScript类型/接口

基于常量ROUTES生成带参数校验的路由类型

给定如下TypeScript常量:

const ROUTES = {
  PAGE_NO_PARAMS: '/hello/page/two',
  PAGE_R: '/about/:id',
  PAGE_Z: '/page/page/:param/:id',
  PAGE_N: '/who/:x/:y/:z/page',
} as const

能否基于这个常量,为每条路由生成对应的类型/接口,限制开发者仅能传入该路由的合法参数?也就是要生成一个和以下RouteAndParams效果完全一致的类型,将原本可能出现的运行时错误提前拦截在编译阶段:

interface PageNoParams {
   route: '/hello/page/two'  // 无参数
}

interface Param1 {
   route: '/about/:id',
   params: { id: string } // 必填参数
}

interface PAGE_Z {
   route: '/page/page/:param/:id',
   params: { id: string; param: string } // 必填参数
}

interface Param3 {
   route: '/who/:x/:y/:z/page',
   params: { x: string; y: string; z: string } // 必填参数
}

type RouteAndParams = PageNoParams | Param1 | PAGE_Z | Param3;

使用示例及预期结果

  • 以下代码不应报错:
const routeWithParams: RouteAndParams = {
   route: '/page/page/:param/:id',
   params: { 'param': 'blah', 'id': 'xxx' }
}
  • 以下代码应报错(存在未预期的参数x):
const routeWithParams: RouteAndParams = {
   route: '/about/:id',
   params: { 'id': 'xxx', 'x': 'xxx' }
}
  • 以下代码应报错(缺少必填参数y):
const routeWithParams: RouteAndParams = {
   route: '/who/:x/:y/:z/page',
   params: { 'x': 'blah', 'z': 'blah' }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:30:54