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
}