To view a live example of the code, visit: https://codesandbox.io/s/typescript-playground-pzl2s
I'm encountering an issue where the object contains two types of properties. At certain points, data is retrieved from the database with only the DRI
child-property. Depending on the parent property, additional child-properties should be added.
The types for the parent properties and the entire object are as follows:
type BalanceModelSectionType = {
DRI: {
AI: number;
AMDR: {
from: number;
to: number;
[index: string]: number;
};
EAR: number;
RDA: number;
UL: number;
unit: string;
[index: string]: string | number | object;
};
quantity: number;
converted: {
quantity: number;
unit: string;
};
percentage: number;
};
type BalanceModelContainerSectionType = {
DRI: {
AI: number;
AMDR: {
from: number;
to: number;
[index: string]: number;
};
EAR: number;
RDA: number;
UL: number;
SC: number;
[index: string]: number | object;
};
percentage: number;
accomplished: number;
};
type BalanceModelType = {
alanine: BalanceModelSectionType;
arginine: BalanceModelContainerSectionType;
// ... many others
[index: string]: BalanceModelSectionType | BalanceModelContainerSectionType;
};
At one point, I receive the following object but it's missing some properties which are added in the forEach
, resulting in a TypeScript error for missing properties:
const model: BalanceModelType = {
alanine: {
DRI: {
AI: 0,
AMDR: {
from: 0,
to: 0
},
EAR: 0,
RDA: 0,
UL: 0,
unit: ``
}
},
arginine: {
DRI: {
AI: 0,
AMDR: {
from: 0,
to: 0
},
EAR: 0,
RDA: 0,
UL: 0,
SC: 0
}
}
};
const defaultSectionValues = {
quantity: 0,
converted: {
quantity: 0,
unit: ``
},
percentage: 0
};
const progressSectionValues = {
percentage: 0,
accomplished: 0
};
Object.keys(model).forEach(sectionName => {
const section = model[sectionName];
/*
How can I dynamically specify the type of a property within an object? */
if (sectionName === `alanine`) {
model[sectionName] = { DRI: section.DRI, ...progressSectionValues }; // Property 'SC' is missing in type
} else {
model[sectionName] = { DRI: section.DRI, ...defaultSectionValues }; // Property 'unit' is missing in type
}
});
If you have suggestions on providing more accurate types for the object or handling types conditionally, your insights would be greatly appreciated.