模板字面量类型深度推理:从路由路径提取参数
利用TypeScript 4.1+的模板字面量类型与条件类型,自动从URL模板中推断动态参数类型。 · 难度:入门 · +10XP
模板字面量类型深度推理:从路由路径提取参数
TypeScript的模板字面量类型不仅能拼接字符串,还能拆分并推理。本主题教你如何实现一个ParseRouteParams<T>类型,将'/users/:id/posts/:postId'这样的路径模板转换为{id: string, postId: string}的对象类型。你将深入理解infer关键字在模板字面量条件类型中的递归用法,并掌握如何匹配命名参数占位符。
type ParseRouteParams<T extends string> =
T extends ${string}:${infer Param}/${infer Rest}
? { [K in Param | keyof ParseRouteParams<Rest>]: string }
: T extends ${string}:${infer Param}
? { [K in Param]: string }
: {};
type Params = ParseRouteParams<'/users/:id/posts/:postId'>;
// 结果: { id: string; postId: string }