Is there a good way in typescript to type a function that will recursively access object properties? Here's a hand-coded example of going two levels deep:
function deepProp<T, K extends keyof T>(obj: T, prop1: K, prop2: keyof T[K]) {
return obj[prop1][prop2];
}
// Example use
const obj = {
user: {
pets: [{
toys: [{
name: "Toughy",
price: 1999
}]
}]
}
} as const
deepProp(obj, "user", "pets");
But I'm looking for a good way to take any number of props in the deepProp function to dive down as deep as necessary. I imagine that function's signature would be something like function deepProp(obj, ...props) { }. Is there a good way to do this? Thanks!