Skip to content

Instantly share code, notes, and snippets.

@yurypaleev
Last active May 17, 2021 10:13
Show Gist options
  • Save yurypaleev/bc9e133c6cb8f3bb49f06be713e5ee25 to your computer and use it in GitHub Desktop.
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
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