Last active
May 17, 2021 10:13
-
-
Save yurypaleev/bc9e133c6cb8f3bb49f06be713e5ee25 to your computer and use it in GitHub Desktop.
Type Path returns all possible variants of the key for the function lodash.get
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 ValueOf<T> = T[keyof T]; | |
type ArrayPath<T> = | |
T extends Array<unknown> | |
? ArrayPath<Omit<T, keyof []>> | |
: T extends object | |
? ValueOf<{ | |
[K in keyof T]: [K] | [K, ...ArrayPath<T[K]>]; | |
}> | |
: never; | |
type StringPath<T> = | |
T extends [...infer A, infer K] | |
? K extends string | number | |
? A extends void[] | |
? K | |
: `${StringPath<A>}${PathVariants<K>}` | |
: never | |
: never; | |
type PathVariants<K extends string | number> = | |
| DotStringPathVariants<K | ArrayStringPathVariants<K>> | |
| ArrayStringPathVariants<K>; | |
type DotStringPathVariants<K extends string | number> = `.${K}`; | |
type ArrayStringPathVariants<K extends string | number> = `[${K}]` | `['${K}']` | `["${K}"]`; | |
export type Path<T> = ArrayPath<T> | StringPath<ArrayPath<T>>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment