Skip to content

Instantly share code, notes, and snippets.

@hugoaboud
Created March 31, 2023 00:54
Show Gist options
  • Save hugoaboud/adfcf7fb6de8a3e76ad7b91f4ca180eb to your computer and use it in GitHub Desktop.
Save hugoaboud/adfcf7fb6de8a3e76ad7b91f4ca180eb to your computer and use it in GitHub Desktop.
Generic Type that recursively flattens a Type by merging property names with dots
type DeepKeys<M> = {
[J in keyof M as `${J & string}${
M[J] extends Record<string, any> ?
M[J] extends {constructor: M[J]} ? '' :
M[J] extends Array<any> ? '' :
`.${keyof DeepKeys<M[J]> & string}` : ''
}`]:
M[J] extends Record<string, any> ? M : M[J]
}
type DeepType<M, K> = K extends `${infer X}.${infer Y}` ?
DeepType<M[X & keyof M], Y> :
M[K & keyof M]
type Flatten<M, Keys=DeepKeys<M>> = {
[K in keyof Keys]:
Keys[K] extends Record<string, any> ?
DeepType<Keys[K], K> :
Keys[K]
}
// ---
type A = {
name: string,
age: number,
company: {
name: string,
is_admin: boolean,
address: {
city: 'pindamomnhangaba' | 'itu',
street: string,
}
}
}
type B = Flatten<A>
// type B = {
// name: string;
// age: number;
// "company.name": string;
// "company.is_admin": boolean;
// "company.address.city": "pindamomnhangaba" | "itu";
// "company.address.street": string;
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment