TypeScript: Obtenga un valor de propiedad profundamente anidado usando la matriz
Me gustaría declarar una función que puede tomar un objeto más una matriz de claves de propiedad anidadas y derivar el tipo del valor anidado como el tipo de retorno de la función.
p.ej
const value = byPath({ state: State, path: ['one', 'two', 'three'] });
// return type == State['one']['two']['three']
const value2 = byPath({ state: State, path: ['one', 'two'] });
// return type == State['one']['two']
Lo mejor que he podido reunir es lo siguiente, pero es más detallado de lo que me gustaría que fuera, y tengo que agregar una sobrecarga de funciones para cada nivel de anidamiento.
export function byPath<
K1 extends string,
R
>({ state, path }: {
state: {[P1 in K1]?: R},
path: [K1]
}): R;
export function byPath<
K1 extends string,
K2 extends string,
R
>({ state, path }: {
state: {[P1 in K1]?: {[P2 in K2]?: R}},
path: [K1, K2]
}): R;
export function byPath<
K1 extends string,
K2 extends string,
K3 extends string,
R
>({ state, path }: {
state: {[P1 in K1]?: {[P2 in K2]?: {[P3 in K3]?: R}}},
path: [K1, K2, K3]
}): R;
export function byPath<R>({ state, path }: { state: State, path: string[] }): R | undefined {
// do the actual nested property retrieval
}
Existe una manera más simple / mejor de hacer esto?