Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kjaer/701d5ca0bf09d2793f32949913416a80 to your computer and use it in GitHub Desktop.
Save Kjaer/701d5ca0bf09d2793f32949913416a80 to your computer and use it in GitHub Desktop.
// https://stackoverflow.com/a/72366029/5018572
type Nested = {
foo: string;
bar: { baz: number; };
squick: { squeck: string; squawk: boolean; };
garble: { gobble: string; };
};
type Example = {
node1: {
node2: {
bla: number;
node3?: {
node4: {
title: string;
};
};
};
};
}
type Flatten<T extends object> = {
[K in keyof T]-?: (
x: NonNullable<T[K]> extends infer V
? V extends object
? V extends readonly any[]
? Pick<T, K>
: Flatten<V> extends infer FV
? {
[P in keyof FV as `${Extract<K, string | number>}.${Extract<P, string | number>}`]: FV[P]
}
: never
: Pick<T, K>
: never
) => void
} extends Record<keyof T, (y: infer O) => void>
? O extends unknown
? { [K in keyof O]: O[K] }
: never
: never
type Unnested = Flatten<Nested>;
type UnnestedExample = Flatten<Example>;
@Kjaer
Copy link
Author

Kjaer commented Jun 1, 2023

Flatten is a sweet example of using recursion in mapped type. It does not comes default with it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment