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)

All DEV content is created by the community!

Hey, if you're landing here for the first time, you should know that this website is a global community of folks who blog about their experiences to help folks like you out.

Sign up now if you're curious. It's free!