TypeScript中如何校验函数入参字符串是否匹配对象路径并实现自动补全
实现方案
1. 类型层面实现路径校验与自动补全
通过TypeScript递归类型提取目标对象所有层级的点分路径,作为函数入参的类型约束,即可同时实现编译阶段的路径合法性校验、编辑器自动补全能力。
首先定义通用递归工具类型DeepKeyof<T>:
// 递归提取对象所有层级的点分路径联合类型 type DeepKeyof<T, Prefix extends string = ''> = T extends object ? { [K in keyof T & string]: Prefix extends '' ? K | DeepKeyof<T[K], `${K}`> : `${Prefix}.${K}` | DeepKeyof<T[K], `${Prefix}.${K}`> }[keyof T & string] : never
改造目标函数,绑定路径类型约束:
// 加as const让TypeScript精确推导对象结构,避免类型拓宽 const obj = { "hello": "hello", "company": { "employee": { "tech": "tech team", "sales": "sales team" } }, } as const // 入参path的类型自动推导为obj所有有效路径的联合类型 function getString<T extends DeepKeyof<typeof obj>>(path: T) { let result: any = obj path.split(".").forEach((k) => { if (!result[k]) return result = result[k] }) return result }
实现效果完全匹配需求:
- 调用
getString("hello"):路径合法,TypeScript无报错 - 调用
getString("howdy"):路径不存在,TypeScript直接抛出类型错误 - 输入
getString("company.em")时,编辑器会自动弹出补全选项:company.employee、company.employee.tech、company.employee.sales
2. 运行时路径校验
TypeScript的类型校验仅在编译阶段生效,如果入参是运行时传入的动态字符串,可补充运行时校验逻辑避免错误:
function getString<T extends DeepKeyof<typeof obj>>(path: T) { const keys = path.split(".") let result: any = obj for (const k of keys) { if (result === null || typeof result !== 'object' || !(k in result)) { throw new Error(`路径${path}不存在于目标对象中`) } result = result[k] } return result }
内容的提问来源于stack exchange,提问作者HelloWorldEngineer
相关产品推荐
相关产品推荐

