/** * 模式配置类型定义 */ type PatternConfig = readonly [key: string, pattern: string, defaultValue?: string]; /** * 根据模式配置推断返回类型 */ type InferResultType = { [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(patterns: T, value?: string): InferResultType { 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] = (groups[key] ?? defaultValue) as any; return values; }, {} as InferResultType); }