Skip to content

Instantly share code, notes, and snippets.

@nielk
Last active January 24, 2018 10:01
Show Gist options
  • Save nielk/306cf8bf5d305ad3f6d0ca44b5629030 to your computer and use it in GitHub Desktop.
Save nielk/306cf8bf5d305ad3f6d0ca44b5629030 to your computer and use it in GitHub Desktop.
safe-access-object.ts
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