Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem!
My goal is to set the property names of an object dynamically using variables. Let me illustrate with an example -> https://codepen.io/Gesma94/pen/xmwMzY
const series = {
data: [
{map1: "People reached", map2: 200},
{map1: "People who called", map2: 117},
{map1: "Contract signed", map2: 77}
],
mapping: {
stage: "map1",
values: "map2"
}
};
const myPar = document.getElementById("myPar");
const { stage: stageLabel, values: valuesLabel} = series.mapping;
series.data.forEach((sample: any, index: number) => {
myPar.innerHTML = myPar.innerHTML + "<br>" + sample[stageLabel];
});
Within the forEach
, I'm using sample: any
.
I want to define the type of sample
based on the retrieved information rather than using any
. Essentially, something like:
sample: {stageLabel: string, valueLabel: number}
. However, TypeScript doesn't recognize these properties at compile time. So, I can't specify sample: {map1: string, map2: number}
, but instead, looking for some aliasing technique.
Despite TypeScript limitations in evaluating variables, my aim is to use aliases like sample.stageLabel
and sample.valueLabel
where these are translated into actual properties like sample.map1
during runtime.
Hoping I've articulated my question clearly enough to grasp it.