Skip to content

Instantly share code, notes, and snippets.

@guiseek
Created December 6, 2023 16:55
Show Gist options
  • Save guiseek/597d9d8a9b2a5c26d35c074c0634c61b to your computer and use it in GitHub Desktop.
Save guiseek/597d9d8a9b2a5c26d35c074c0634c61b to your computer and use it in GitHub Desktop.
Deep Pick
export const deepPick = <T extends object>(value: T) => {
return <K extends keyof T & string>(path: K) => {
return path.split('.').reduce<T[K]>((prev, curr) => {
return typeof prev[curr] === 'object' ? prev[curr] : prev;
}, value as T[K]);
};
};
export function deep<T extends object>(value: T) {
// prettier-ignore
function pick<K extends keyof T & string, K2 extends keyof T[K] & string, K3 extends keyof T[K][K2] & string, K4 extends keyof T[K][K2][K3] & string>(path: `${K}.${K2}.${K3}.${K4}`): T[K][K2][K3]
// prettier-ignore
function pick<K extends keyof T & string, K2 extends keyof T[K] & string, K3 extends keyof T[K][K2] & string>(path: `${K}.${K2}.${K3}`): T[K][K2][K3]
// prettier-ignore
function pick<K extends keyof T & string, K2 extends keyof T[K] & string>(path: `${K}.${K2}`): T[K][K2]
// prettier-ignore
function pick<K extends keyof T & string>(path: K): T[K]
function pick<K extends keyof T & string>(...path: K[]) {
return path
.join()
.split('.')
.reduce<T[K]>((prev, curr) => {
return typeof prev[curr] === 'object' ? prev[curr] : prev;
}, value as T[K]);
}
return pick;
}
const pick = deep({ a: { b: { c: 'gui' } } });
pick('a.b.c');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment