Last active
January 24, 2018 10:01
-
-
Save nielk/306cf8bf5d305ad3f6d0ca44b5629030 to your computer and use it in GitHub Desktop.
safe-access-object.ts
This file contains hidden or 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, | |
K0 extends keyof T, | |
K1 extends keyof T[K0], | |
K2 extends keyof T[K0][K1], | |
K3 extends keyof T[K0][K1][K2], | |
K4 extends keyof T[K0][K1][K2][K3], | |
K5 extends keyof T[K0][K1][K2][K3][K4]> | |
(obj: T, k0: K0, k1?: K1, k2?: K2, k3?: K3, k4?: K4, k5?: K5) { | |
return Array.from(arguments).slice(1).reduce((prefix, val) => (prefix && prefix[val]) ? prefix[val] : null, obj) | |
} | |
interface A { | |
b: { | |
c: string | |
} | |
} | |
const a: A = { b: { c: 'hello' } } | |
console.log(get(a, 'b', 'c')) // "hello" | |
console.log(get(a, 'b', 'd')) // TS error et retourne null | |
// @TODO: | |
// - Peut être que tu peux avoir une seule implémentation en js avec des varargs, et juste un fichier de typage avec les différentes arites | |
// - si tu overload pour chaque arité, tu devrais pouvoir typer le résultat |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment