Is there an efficient method in TypeScript to type a function that can recursively access object properties? The provided example delves two levels deep:
function fetchNestedProperty<T, K extends keyof T>(obj: T, prop1: K, prop2: keyof T[K]) {
return obj[prop1][prop2];
}
// Sample usage
const data = {
user: {
pets: [{
toys: [{
name: "Rex",
price: 2999
}]
}]
}
} as const
fetchNestedProperty(data, "user", "pets");
However, I am seeking a robust approach to allow any number of props
in the fetchNestedProperty
function to traverse into nested objects effortlessly. Ideally, the function's declaration would resemble
function fetchNestedProperty(obj, ...props) { }
. Is there an effective strategy to achieve this functionality? Thank you for your insights!