Skip to content

Commit 6ac07d5

Browse files
committed
feat(types): add utility to convert string paths into nested object types
1 parent 5986dad commit 6ac07d5

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

primitives/type-utils/src/utils.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,3 +194,18 @@ type PathsShape<T, Index extends number = number, P extends string = '', Depth e
194194

195195
export type AllPathsShape<T> = MergeUnion<PathsShape<T>>;
196196
export type AllPathsKeys<T> = keyof AllPathsShape<T> & string;
197+
198+
// 工具:把 "a.b.c" 转成 { a: { b: { c: V } } }
199+
type KeyToNestedObject<K extends string, V> = K extends `${infer Head}.${infer Rest}`
200+
? { [P in Head]: KeyToNestedObject<Rest, V> }
201+
: { [P in K]: V };
202+
203+
// 合并交叉类型 {a:{b:V}} & {a:{c:V}} → {a:{b:V;c:V}}
204+
type Merge<T> = {
205+
[K in keyof T]: T[K];
206+
};
207+
208+
// 核心:把一组路径 keys 转换成层级对象
209+
export type KeysToNestedObject<Keys extends readonly string[], V> = Merge<
210+
Keys[number] extends infer K ? (K extends string ? KeyToNestedObject<K, V> : never) : never
211+
>;

0 commit comments

Comments
 (0)