Given is a tuple of some keys like ["a", "b", "c"]
and a nested object with those keys as properties {a: {b: {c: number}}}
. How do you recursively use the members of the tuple as index in typescript?
A implementation without proper typing:
function recursivePluck(ob: any, tuple: any[]): any {
for (let index of tuple) {
ob = ob[index]
}
return ob
}
How do you type the above code?
I have tried the following
type RecursivePluck<
Tuple extends string[],
Ob extends {[key in string]: any},
TupleWithoutFirst extends SliceStartQuantity<Tuple, 1> = SliceStartQuantity<Tuple, 1>
>
= TupleWithoutFirst extends [] ? Ob[Tuple[0]] : RecursivePluck<TupleWithoutFirst, Ob[Tuple[0]]>
But this errors Type alias 'RecursivePluck' circularly references itself.
Note that
SliceStartQuantity
is fromtypescript-tuple
(npm)
Here the solution, it covers type safety of the argument and of the return type:
The Playground