0

I have the following object:

const myObject = {
  one: {
    fixed: {
      a: 1
    }
  },
  two: {
    fixed: {
      b: true
    }
  },
  three: {
    fixed: {
      c: 'foo'
    }
  }
}

How can I use this object, to create a type equivalent to the following:

type MyUnionType = {
  a: number
  b: boolean
  c: string
}

?

1 Answer 1

3

You can use

type MyObject = typeof myObject;

type MyUnionType = {
    [T in keyof MyObject as keyof MyObject[T]["fixed"]]: MyObject[T]["fixed"][keyof MyObject[T]["fixed"]]
}

From the varying top level properties as a type parameter (eg (one), it first extracts the key of the nested object (eg a or b) and then (verbosely) accesses the nested value associated with that key.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thank you:) I made a playground from your answer. Check it out here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.