Home > Back-end >  Use typescript to create union object of keys in objects
Use typescript to create union object of keys in objects

Time:02-03

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
}

?

CodePudding user response:

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.

  •  Tags:  
  • Related