Created
May 20, 2022 05:53
-
-
Save rakeshta/a2731f7469480455acd6941931cd75ab to your computer and use it in GitHub Desktop.
Awesome utility type copied from `native-base` that extracts the key paths to the leaves of a nested object type into a new type
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
/** | |
* Joins two types with a `.`. | |
* | |
* _Pure inspirational typescript wizardry!_ | |
* @note this was copied from the type system of `native-base`. | |
*/ | |
export type Join<K, P> = K extends string | number ? P extends string | number ? `${K}${'' extends P ? '' : '.'}${P}` : never : never; | |
/** | |
* Recursively flattens the keys in the object to key-paths of the leaf nodes. | |
* | |
* **Example** | |
* ```typescript | |
* const colors = { | |
* primary: { | |
* 100: 'red', | |
* 200: 'pink', | |
* }, | |
* secondary: { | |
* 100: 'blue', | |
* 200: 'lightBlue', | |
* } | |
* } | |
* | |
* type ColorKeys = LeafKeyPaths<typeof colors>; | |
* | |
* // the above is equivalent to this | |
* type ColorKeys = 'primary.100' | 'primary.200' | 'secondary.100' | 'secondary.200'; | |
* ``` | |
* | |
* _Pure inspirational typescript wizardry!_ | |
* @note this was copied from the type system of `native-base`. | |
*/ | |
export type LeafKeyPaths<T> = T extends object ? { | |
[K in keyof T]-?: Join<K, LeafKeyPaths<T[K]>>; | |
}[keyof T] : ''; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment