Typescript如何为Firestore路径关联对应接口,实现setValue参数类型校验
解决方案
第一步:实现路径到类型的映射工具类型
因为TS不支持直接将模板字面量类型作为对象类型的键,我们可以通过条件类型+模板字面量匹配实现映射逻辑:
type PathToType<P extends FsPath> = P extends `badges/${string}` ? ServerBadge : P extends 'entities' | `entities/${string}` ? ServerEntity : never;
第二步:改造setValue为泛型函数
把路径作为泛型参数,让TS可以根据传入的具体路径值推导对应value的类型:
function setValue<P extends FsPath>(path: P, value: PathToType<P>) { // 原有业务逻辑 }
效果验证
此时你的错误调用会正常触发TS报错:
const badge: ServerBadge = { level: 4, label: 'Best badge' }; // 此处会报错:类型ServerBadge的参数不能赋给类型ServerEntity的参数 setValue('entities/qs89sdjdziU', badge);
补充:可维护的类PathMap写法
如果你希望像写对象键值对一样维护路径与类型的映射关系,避免嵌套条件类型难以维护,可以用如下方式封装:
// 定义映射规则,元组第一项为路径匹配规则,第二项为对应类型 type PathMapRules = [ [match: `badges/${string}`, type: ServerBadge], [match: 'entities' | `entities/${string}`, type: ServerEntity] ] // 通用工具类型,遍历规则匹配路径返回对应类型 type PathToType<P extends string> = PathMapRules extends [infer First, ...infer Rest extends any[][]] ? First extends [infer Match, infer Type] ? P extends Match ? Type : PathToType<P, Rest> : never : never;
后续新增路径类型只需要在PathMapRules里加新的元组项即可,不需要修改匹配逻辑。
内容的提问来源于stack exchange,提问作者Maslow
相关产品推荐
相关产品推荐

