| 12345678910111213141516171819202122232425262728293031 |
- /**
- * 模式配置类型定义
- */
- type PatternConfig = readonly [key: string, pattern: string, defaultValue?: string];
- /**
- * 根据模式配置推断返回类型
- */
- type InferResultType<T extends readonly PatternConfig[]> = {
- [K in T[number] as K extends readonly [infer Key, ...any[]] ? Key : never]: K extends readonly [any, any, infer Default]
- ? Default extends string
- ? string
- : string | undefined
- : string | undefined;
- };
- /**
- * 分析函数 - 根据 patterns 参数类型确定返回类型
- * @param patterns 模式配置数组
- * @param value 要解析的字符串
- * @returns 解析后的对象,类型根据patterns自动推断
- */
- export function analysis<T extends readonly PatternConfig[]>(patterns: T, value?: string): InferResultType<T> {
- const regex = patterns.map(([key, pattern]) => `(?:${key}:(?<${key}>${pattern})[;$]?)?`).join('');
- const groups = (value || '').match(new RegExp(`^${regex}`))?.groups ?? {};
- return patterns.reduce((values, [key, _, defaultValue]) => {
- values[key as keyof InferResultType<T>] = (groups[key] ?? defaultValue) as any;
- return values;
- }, {} as InferResultType<T>);
- }
|