I have an enum:
enum REPORT_PARAMETERS {
DEFECT_CODE = 'DEFECT_CODE',
ORGANIZATION = 'ORGANIZATION'
}
And I have an object and a map of functions, which use this enum as keys:
interface Form {
[REPORT_PARAMETERS.DEFECT_CODE]: number;
[REPORT_PARAMETERS.ORGANIZATION]: string;
}
const form = {
[REPORT_PARAMETERS.DEFECT_CODE]: 1,
[REPORT_PARAMETERS.ORGANIZATION]: '1'
}
const formMappers: {
[key in REPORT_PARAMETERS]: () => Form[key];
} = {
[REPORT_PARAMETERS.DEFECT_CODE]: () => 123,
[REPORT_PARAMETERS.ORGANIZATION]: () => '123'
}
Then I want to iterate enum to map form:
const reports: REPORT_PARAMETERS[] = [
REPORT_PARAMETERS.DEFECT_CODE,
REPORT_PARAMETERS.ORGANIZATION
]
reports.forEach((type) => {
// At this point I assume that 'type' is a specific value of enum,
// so I try to use this value to index both objects, but it doesn't work
form[type] = formMappers[type]();
})
Here is TypeScript Playground to see it in action