Home > other >  How infer certain property from nested objects as union?
How infer certain property from nested objects as union?

Time:11-28

I have next object with question, and inside each question I have property answer, so how can I inver it as union types?

Example:

const data = {
  question1: {
    answer: 'answer1',
  },
   question2: {
    answer: 'answer2',
  },
  question3: {
    answer: 'answer3',
  },
}

Expected result:

type Key = 'answer1' | 'answer2' | 'answer3'

CodePudding user response:

Probably better solutions would exist. But this will be an answer.

const data = {
  question1: {
    answer: 'answer1',
  },
   question2: {
    answer: 'answer2',
  },
  question3: {
    answer: 'answer3',
  },
} as const

type Key = typeof data[keyof typeof data]['answer']
  • Related