DevOverflow
DevOverflow

Reputation: 1712

How infer certain property from nested objects as union?

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'

Upvotes: 0

Views: 96

Answers (1)

dogukyilmaz
dogukyilmaz

Reputation: 615

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

Upvotes: 1

Related Questions