Typescript Flatten Object Type

tylim88

Acid Coder

Posted on June 29, 2023

Typescript Flatten Object Type
type ToPaths<T, P extends string = ''> = T extends Record<number, unknown>
    ? {
        [K in keyof T]: ToPaths<T[K], `${P}${K & string}.`>
    }[keyof T]
    : { path: P extends `${infer P}.` ? P : never; type: T }

type FromPaths<T extends { path: string; type: unknown }> = {
    [P in T['path']]: Extract<T, { path: P }>['type']
}

type A = FromPaths<ToPaths<{
//  ^?
    a: 1,
    b: {
        c: 2,
        d: Record<string, {
            e: 3,
            f: 4,
        }>,
        g: 5,
    },
    h: {
        i: {
            j: 6,
        },
    },
}>>


Enter fullscreen mode Exit fullscreen mode

Image description
playground

💖 💪 🙅 🚩
tylim88
Acid Coder

Posted on June 29, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related