I have 3 objects a, b and c, each of them has a prop field, whose value can be anything.
const a = { prop: { foo: 'bar', bar: true } }
const b = { prop: { baz: 1234 } }
const c = { prop: true }
These objects are organized into sections:
const sectionA = { a, b }
const sectionB = { c }
const allSections = {sectionA, sectionB}
I want to construct the following object dynamically:
const myObject = {
sectionA: {
a: {foo: 'bar', bar: true},
b: {baz: 1234}
},
sectionB: {
c: true
}
}
I.e. correctly organized into nested objects, but without the prop field.
Here's what I did:
type ObjectWithProp = { prop: any }
type ObjectTypes<Section extends {[index:string]: ObjectWithProp}> = {
[K in keyof Section]: Section[K]['prop']
}
type AllSectionTypes<AllSection extends { [index: string]: { [index: string]: ObjectWithProp } }> = {
[K in keyof AllSection]: ObjectTypes<AllSection[K]>
}
const result = Object.keys(allSections).reduce((outerAcc, _key) => {
const key = _key as keyof typeof allSections;
const section = allSections[key];
outerAcc[key] = Object.keys(section).reduce((innerAcc, _objectName) => {
const objectName = _objectName as keyof typeof section;
const obj = section[_objectName];
innerAcc[objectName] = obj.prop;
return innerAcc;
}, {} as ObjectTypes<typeof section>);
return outerAcc;
}, {} as AllSectionTypes<typeof allSections>)
At line const objectName = _objectName as keyof typeof section;, objectName is unfortunately never (logical since there are no common fields between the objects). But then I cannot do innerAcc[objectName].
How can I solve that?
reduceas generic in the keyKoftypeof allSectionsand the keyPoftypeof allSections[K], the compiler can't seem to reason abouttypeof allSections[K][P]and how it relates toAllSectionTypes<typeof allSections>[K][P].as any), how would you assert?