Last active
December 28, 2023 18:48
-
-
Save nasheomirro/c8c8c25da0803e7515fc6c2cf7c5b2c8 to your computer and use it in GitHub Desktop.
A utility to flatten keys just like how react-hook-form does it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type FlattenKeys<T extends Record<string, any>, prefix extends string = ''> = { | |
[key in keyof T]: key extends string | |
? T[key] extends object | |
? `${prefix}${key}` | FlattenKeys<T[key], `${prefix}${key}.`> | |
: `${prefix}${key}` | |
: never; | |
}[keyof T]; | |
// and to use it: | |
type Data = { | |
title: string; | |
meta: { | |
dateCreated: string; | |
author: { | |
username: string; | |
userId: string; | |
}; | |
}; | |
}; | |
// "title" | "meta" | "meta.author" | "meta.author.userId" | ... | |
type Keys = FlattenKeys<Data>; | |
// for arrays being inside, you need to remove their types from the union | |
type RemoveNonString<T> = T extends string ? T : never; | |
type FixedData = RemoveNonString<FlattenKeys<Data>>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment