Lodash has the function get()
, which extracts a value from a complex object:
const object = { 'a': [{ 'b': { 'c': 3 } }] };
const n: 3 = _.get(object, 'a[0].b.c');
Lodash types get
as:
type PropertyName = string | number | symbol;
type PropertyPath = Many<PropertyName>;
get(object: any, path: PropertyPath, defaultValue?: any): any;
Which is, in my opinion, somewhat weak. Monocle-ts solves a similar problem by just listing the first five or so possibilities:
export interface LensFromPath<S> {
<
K1 extends keyof S,
K2 extends keyof S[K1],
K3 extends keyof S[K1][K2],
K4 extends keyof S[K1][K2][K3],
K5 extends keyof S[K1][K2][K3][K4]
>(
path: [K1, K2, K3, K4, K5]
): Lens<S, S[K1][K2][K3][K4][K5]>
<K1 extends keyof S, K2 extends keyof S[K1], K3 extends keyof S[K1][K2], K4 extends keyof S[K1][K2][K3]>(
path: [K1, K2, K3, K4]
): Lens<S, S[K1][K2][K3][K4]>
<K1 extends keyof S, K2 extends keyof S[K1], K3 extends keyof S[K1][K2]>(path: [K1, K2, K3]): Lens<S, S[K1][K2][K3]>
<K1 extends keyof S, K2 extends keyof S[K1]>(path: [K1, K2]): Lens<S, S[K1][K2]>
<K1 extends keyof S>(path: [K1]): Lens<S, S[K1]>
}
Which is great as far as it goes, but it only goes so far. Is there not a cleaner way?