TypeScript: obtenha um valor de propriedade profundamente aninhado usando o array
Gostaria de declarar uma função que pode pegar um objeto mais uma matriz de chaves de propriedades aninhadas e derivar o tipo do valor aninhado como o tipo de retorno da funçã
por exemplo
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']
O melhor que consegui reunir é o seguinte, mas é mais detalhado do que gostaria e preciso adicionar uma sobrecarga de função para todos os níveis de aninhament
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 uma maneira mais simples / melhor de fazer isso?