如何从TypeScript嵌套常量对象递归推导目标类型?
如何从嵌套常量对象递归生成目标布尔结构类型?
问题背景
现有如下只读常量对象:
const rights = [{ label: 'Dashboard', value: 'dashboard', children: [ { label: 'Statistics', value: 'stats', children: [ { label: 'Read', value: 'read', }, { label: 'Write', value: 'write', }, ], }, { label: 'CSV Export', value: 'csvExport', children: [ { label: 'Read', value: 'read', }, { label: 'Write', value: 'write', }, ], }, ], }] as const;
需要从该对象推导出如下嵌套布尔结构类型:
{ dashboard: { stats: { read: boolean, write: boolean, }, csvExport: { read: boolean, write: boolean, }, } }
当前尝试的问题
你目前的代码存在几个关键问题:
ObjectType = typeof object是错误的,应该是typeof rightsCurrentNode的定义没有匹配as const生成的只读字面量类型,导致类型约束不匹配- 递归类型中
T[number]['children']会取所有节点children的联合类型,无法正确对应单个节点的子结构
你的尝试代码:
type ObjectType = typeof object; // 错误:应该是typeof rights type CurrentNode = { readonly label: string; readonly value: string; readonly children?: CurrentNode[]; }; type TransformToBoolean2<T extends CurrentNode[]> = { [K in T[number]['value']]: T[number]['children'] extends CurrentNode[] ? TransformToBoolean2<T[number]['children']> : boolean; }; type booleanObject = TransformToBoolean2<ObjectType>;
解决方案
可以通过精准匹配只读节点类型+递归遍历单个节点的子结构来实现:
// 从常量中自动推导节点类型,避免手动定义的偏差 type RightsNode = typeof rights[number]; // 递归转换类型:处理节点数组 type TransformRights<T extends readonly RightsNode[]> = { // 遍历每个节点的value作为键 [K in T[number]['value']]: // 找到当前value对应的节点 Extract<T[number], { value: K }> extends { children: infer C } // 如果有children,递归处理children数组 ? C extends readonly RightsNode[] ? TransformRights<C> : boolean // 没有children则为boolean : boolean; }; // 生成目标类型 type BooleanRights = TransformRights<typeof rights>;
验证结果:BooleanRights的类型完全符合预期,会生成:
type BooleanRights = { dashboard: { stats: { read: boolean; write: boolean; }; csvExport: { read: boolean; write: boolean; }; }; }
关键说明:
- 使用
typeof rights[number]自动推导节点类型,完美匹配as const生成的只读字面量 Extract<T[number], { value: K }>用于精准找到当前键对应的节点,避免联合类型的干扰- 递归时针对单个节点的children进行处理,确保层级结构正确映射
内容的提问来源于stack exchange,提问作者RandomDude1234
相关产品推荐
相关产品推荐

