Monday, 13 September 2021

Typescript: deep keyof of a nested object, with related type

I'm looking for a way to have all keys / values pair of a nested object.

(For the autocomplete of MongoDB dot annotation key / value type)

interface IPerson {
    name: string;
    age: number;
    contact: {
        address: string;
        visitDate: Date;
    }
}

Here is what I want to achieve: to make it becomes

type TPerson = {
    name: string;
    age: number;
    contact: { address: string; visitDate: Date; }
    "contact.address": string;
    "contact.visitDate": Date;
}

What I have tried:

In this answer, I can get the key with Leaves<IPerson>. So it becomes 'name' | 'age' | 'contact.address' | 'contact.visitDate'.

And in another answer from @jcalz, I can get the deep, related value type, with DeepIndex<IPerson, ...>.

Is it possible to group them together, to become type like TPerson?



from Typescript: deep keyof of a nested object, with related type

No comments:

Post a Comment