← 中文资源

简体中文版本

模板字面量类型路由解析器

用模板字面量类型与 infer 在类型层解析路由:路径参数自动提取为 string 字段,运行时正则只写一次。

阅读英文原文

实现说明

底层就是函数 matchRoute。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 matchRoute。

核心语句

TRoute extends `${infer _Start}:${infer Param}/${infer Rest}`
  ? { [K in Param | keyof ExtractParams<Rest>]: string }
return groups ? (groups as ExtractParams<TRoute>) : null;
: TRoute extends `${infer _Start}:${infer Param}`
  ? { [K in Param]: string }

代码示例

type ExtractParams<TRoute extends string> =
  TRoute extends `${infer _Start}:${infer Param}/${infer Rest}`
    ? { [K in Param | keyof ExtractParams<Rest>]: string }
    : TRoute extends `${infer _Start}:${infer Param}`
      ? { [K in Param]: string }
      : // 无参数路由
        Record<never, never>;

type UserRoute = ExtractParams<'/users/:userId/posts/:postId'>;
// { userId: string; postId: string }

function matchRoute<TRoute extends string>(
  route: TRoute,
  path: string,
): ExtractParams<TRoute> | null {
  const pattern = new RegExp(
    '^' + route.replace(/:([A-Za-z]+)/g, '(?<$1>[^/]+)') + '$',
  );
  const groups = pattern.exec(path)?.groups;
  return groups ? (groups as ExtractParams<TRoute>) : null;
}

const params = matchRoute('/users/:userId/posts/:postId', '/users/42/posts/7');
console.log(params?.userId, params?.postId);

const miss = matchRoute('/health', '/healthz');
console.log(miss);