Can the structure of this type be flattened?
type MySchema = {
fields: {
hello: {
type: 'Group'
fields: {
world: {
type: 'Group'
fields: { yay: { type: 'Boolean' } }
}
}
}
world: { type: 'Boolean' }
}
}
Transforming it into:
type MyFlattenedSchema = {
hello: { type: 'Group' }
'hello.world': { type: 'Group' }
'hello.world.yay': { type: 'Boolean' }
world: { type: 'Boolean' }
}
I've been attempting to solve this for a couple of days now, but all I'm getting is a flattened union:
type FSchema = { type: string; fields?: Record<string, FSchema> }
type GetPathAndChilds<
T extends Record<string, FSchema>,
PK extends string | null = null
> = {
[FN in keyof T & string]-?: {
path: PK extends string ? `${PK}.${FN}` : `${FN}`
type: T[FN]['type']
// config: T[K]
childs: T[FN] extends { fields: Record<string, FSchema> }
? GetPathAndChilds<
T[FN]['fields'],
PK extends string ? `${PK}.${FN}` : `${FN}`
>
: never
}
}[keyof T & string]
type FlattenToUnion<T extends { path: string; type: string; childs: any }> =
T extends {
path: infer P
type: infer U
childs: never
}
? { [K in P & string]: { type: U } }
: T extends { path: infer P; type: infer U; childs: infer C }
? { [K in P & string]: { type: U } } | FlattenToUnion<C>
: never
type MySchemaToUnion = FlattenToUnion<GetPathAndChilds<TestSchema['fields']>>
// | { hello: { type: 'Group' } }
// | { 'hello.world': { type: 'Group' } }
// | { 'hello.world.yay': { type: 'Boolean' } }
// | { world: { type: 'Boolean' } }
After researching on stackoverflow, the error 'Type instantiation is excessively deep and possibly infinite' is what I keep encountering.