如何解决用于将“扁平化”对象的键递归地重新映射到嵌套对象中的类型使用模板文字
我试图将类型表达为一个函数,该函数将带有键的对象作为点分隔路径并返回一个新对象,其中所有子路径都被展开。我无法理解如何在递归“解构”它们的同时保留给定路径的原始类型。
// Dummy structure
const flattenedObject = {
'd.a': 1,'d.b': true,};
type FlattenedObject = typeof flattenedObject;
// Expected type (or union of sub-paths: `{ d: { a: number } } | { d: { b: boolean } }`)
interface NestedObject {
d: {
a: number;
b: boolean;
}
}
// Attempt
type MapNestedKeys<R,N extends keyof R = keyof R,N0 = N> = N0 extends string
? N0 extends `${infer K1}.${infer K2}`
? { [K in N as `${K1}`]: MapNestedKeys<R,N,K2> }
: { [K in N as N0]: R[K] }
: {};
// Gives union,but types for nested keys are now union on all key types
type Test = MapNestedKeys<FlattenedObject>;
解决方法
另一种在路径的不同深度下效果更好的替代方法(例如“d.a.c”)
type MapNestedKeys<T,P = keyof T> =
P extends `${infer K1}.${infer K2}` & keyof T ?
MapNestedKeys<{[S in K1]: MapNestedKeys<{[S1 in K2]: T[P]}>}> :
P extends string & keyof T ? {[S in P]: T[P]} : {}
,
更新
// Dummy structure
const flattenedObject = {
'a.b.c.d.e': 1,'f.g.h.j.k': true,};
type FlattenedObject = typeof flattenedObject;
type Values<T> = T[keyof T]
type MakeObj<Prop,Value> =
Prop extends string ?
Prop extends `${infer Head}.${infer Tail}` ?
{ [Key in Head]: MakeObj<Tail,Value> }
: Prop extends string ? { [K in Prop]: Value }
: never
: never
type Iterate<Obj> = Values<{
[Prop in keyof Obj]: MakeObj<Prop,Obj[Prop]>
}>
type Result = Iterate<FlattenedObject>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。