Home > Software design >  TypeScript – How to get a union recursively of all nested values of a const object
TypeScript – How to get a union recursively of all nested values of a const object

Time:02-19

How do I get a union type with the nested values from this const object called Data:

const Data = {
 a: {
   x: "valueX"
 },
 b: {
   y: "valueY",
   z: "valueZ"
 }
} as const

type ValuesOf<O> = /* not quite sure how to do this recursively */
type TestValues = ValuesOf<Data> // "valueX" | "valueY" | "valueZ"

CodePudding user response:

Consider this:

const Data = {
  a: {
    x: "valueX"
  },
  b: {
    y: "valueY",
    z: "valueZ"
  }
} as const

type RecursiveValues<T> = {
  [Prop in keyof T]:
  (T[Prop] extends Record<string, any>
    ? RecursiveValues<T[Prop]>
    : T[Prop])
}[keyof T]

type TestValues = RecursiveValues<typeof Data>

// type Test = {
//     valueX: "valueX";
//     valueY: "valueY";
//     valueZ: "valueZ";
// }
type Test = {
  [P in TestValues]: P
}

Playground

  • Related