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

TypeScript中解析多类型URL路径参数为对象并简化代码

支持带类型参数的路径解析与代码简化

实现目标

解析类似"/user/:id(string)/update/:id2(number)/:id3"的路径,未指定类型时参数默认类型为string,最终得到如下类型:

{
  id: string;
  id2: number;
  id3: string;
}

简化后的实现代码

// 定义路径中类型字符串到TS原生类型的映射,可扩展更多类型
type TypeMap = {
  string: string;
  number: number;
};

// 设置默认参数类型为string
type DefaultParamType = TypeMap['string'];

// 解析单个路径段,处理参数的类型标注
type ParsePathSegment<T extends string> = 
  T extends `:${infer ParamName}(${infer TypeStr})`
    ? { [Key in ParamName]: TypeStr extends keyof TypeMap ? TypeMap[TypeStr] : DefaultParamType }
    : T extends `:${infer ParamName}`
      ? { [Key in ParamName]: DefaultParamType }
      : {}; // 非参数段返回空对象,不影响最终交叉结果

// 递归解析整个路径,合并各段的参数类型
type ParsePath<T extends string> = 
  T extends `${infer Segment}/${infer RestPath}`
    ? ParsePathSegment<Segment> & ParsePath<RestPath>
    : ParsePathSegment<T>;

// 测试用例
type TestPath = "/user/:id(string)/update/:id2(number)/:id3";
type ParsedResult = ParsePath<TestPath>;
// 结果:{ id: string; id2: number; id3: string; }

代码说明

  1. 类型映射:TypeMap将路径中的类型标识(如"string")映射为TypeScript原生类型,方便后续扩展boolean、bigint等类型。
  2. 单段解析:ParsePathSegment处理单个路径段,区分带类型标注的参数(:id(type))和无标注参数(:id),未知类型自动 fallback 到默认的string。
  3. 递归合并:ParsePath通过递归拆分路径的/分隔段,将各段的解析结果用交叉类型合并,直接生成最终的参数对象类型,省去了原代码中「元组中转」的步骤,逻辑更简洁。

扩展能力

如果需要支持更多参数类型,只需在TypeMap中添加对应映射即可,例如:

type TypeMap = {
  string: string;
  number: number;
  boolean: boolean;
  bigint: bigint;
};

之后即可解析:isActive(boolean)、:count(bigint)这类参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:07:45