Created
July 27, 2018 12:58
-
-
Save Reshetnyak/08c41e3bd9e8637de1604634d6fe79a0 to your computer and use it in GitHub Desktop.
Safely get deep nested property of object
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
function get< | |
T, | |
K extends keyof T, | |
T1 extends T[K], | |
K1 extends keyof T1, | |
T2 extends T1[K1], | |
K2 extends keyof T2, | |
T3 extends T2[K2], | |
K3 extends keyof T3, | |
R extends T3[K3] | |
>( | |
obj: T, | |
path: [K, K1, K2, K3] | |
): R | |
function get< | |
T, | |
K extends keyof T, | |
T1 extends T[K], | |
K1 extends keyof T1, | |
T2 extends T1[K1], | |
K2 extends keyof T2, | |
R extends T2[K2] | |
>( | |
obj: T, | |
path: [K, K1, K2] | |
): R | |
function get< | |
T, | |
K extends keyof T, | |
T1 extends T[K], | |
K1 extends keyof T1, | |
R extends T1[K1] | |
>( | |
obj: T, | |
path: [K, K1] | |
): R | |
function get< | |
T, | |
K extends keyof T, | |
R extends T[K] | |
>( | |
obj: T, | |
path: [K] | |
): R | |
function get< | |
T, | |
K extends keyof T, | |
R extends T[K] | |
>( | |
obj: T, | |
path: [K] | |
): R{ | |
let res; | |
for (const key of path) { | |
res = obj[key]; | |
if (res) { | |
return res; | |
} | |
} | |
return void 0; | |
}; | |
interface D { | |
dd: number; | |
} | |
interface BB { | |
c: string; | |
d: D; | |
} | |
interface B { | |
aa: number; | |
bb: BB; | |
} | |
interface OO { | |
a: number; | |
b: B; | |
} | |
const oo = { | |
a: 10, | |
b: { | |
aa: 10, | |
bb: { | |
c: 'hello', | |
d: { | |
dd: 11 | |
} | |
} | |
} | |
}; | |
const r = get(oo, ['a']); | |
console.log('r is: ', r); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment