Skip to content

Instantly share code, notes, and snippets.

@rakeshta
Created May 20, 2022 05:53
Show Gist options
  • Save rakeshta/a2731f7469480455acd6941931cd75ab to your computer and use it in GitHub Desktop.
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
/**
* 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