DEV Community

Kay Gosho
Kay Gosho

Posted on

Get object 1 level-down type programmatically in TypeScript

We would like to get object value type.

Assume this object:

const query = { getUserAndBook: { user: { name: 'acro5piano' }, book: { name: 'acro5piano' } } } 
Enter fullscreen mode Exit fullscreen mode

If we would like to get typeof query.getUserAndBook programmatically, we can write like this:

type Query = typeof query.getUserAndBook 
Enter fullscreen mode Exit fullscreen mode

But if the key of query (this time getUserAndBook) may vary, how to pick the type of it?

...We can do:

export type GetObjectOneLevelDownType<T extends {}, K extends keyof T> = { value: T[K] }['value'] 
Enter fullscreen mode Exit fullscreen mode

The trick is that we explicitly set value property and pick it.

The following much simple code does not work:

type GetObjectOneLevelDownType<T extends {}, K extends keyof T> = T[K] 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)