Nick
Nick

Reputation: 16576

Can a typed function recursively access object properties?

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!

Upvotes: 2

Views: 123

Answers (1)

Shlang
Shlang

Reputation: 3230

It is not possible for arbitrary number of keys, but you can make something similar to lodash's get for your needs.

It also possible to use the function in a kind of recursive manner.

The example with mentioned _.get (its type supports up to 4 keys):

const obj = {
    user: {
        pets: [{
            toys: [{
                name: "Toughy",
                price: 1999
            }]
        }]
    }
} as const

const toy1 = _.get(obj, ["user", "pets", 0, "toys"]); // correct type
const toy2 = _.get(obj, ["user", "pets", 0, "toys", 0]); // any :(
const toy3 = _.get(_.get(obj, ["user", "pets", 0, "toys"]), [0]); // correct type :)

Upvotes: 2

Related Questions