loading...

Get object 1 level-down type programmatically in TypeScript

acro5piano profile image Kay Gosho ・1 min read

We would like to get object value type.

Assume this object:

const query = {
  getUserAndBook: {
    user: {
      name: 'acro5piano'
    },
    book: {
      name: 'acro5piano'
    }
  }
}

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

type Query = typeof query.getUserAndBook

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']

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]

Posted on by:

Discussion

markdown guide