从路由映射生成带参数约束的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
相关产品推荐
相关产品推荐

