DEV Community

Kay Gosho
Kay Gosho

Posted on

2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay