Im trying to create an initialise an object with known keys, however the initial empty object {} that I need breaks my typing.
I have a list of value, that I want to use as keys, and I want to initialise an object with those keys. In python i would do something like:
myDict = {key: value for (key, value) in zip(myKeys, [[]]*len(myKeys))}
This should give the myDict the type Record<myKeys, string[]>
In TS, i dont seem to be able to have the same luck, as i need to initialise the object to an empty list before i can populate it with my keys/values. I would rather not need to call it a partial, then coerce it into the correct type.
I have tried:
const allPlanFeatures: Partial<Record<ExtensivePlanHandle, string[]>> = {};
for (const planId of extensivePlanList) {
const features = getFeaturesForPlan(planHandleToMonthly[planId], is4kEnabled, exportFlow);
allPlanFeatures[planId] = features;
}
return allPlanFeatures as Record<ExtensivePlanHandle, string[]>;
and
const allPlanFeatures: Partial<Record<ExtensivePlanHandle, string[]>> =
extensivePlanList.reduce(
(a, planHandle) => ({
...a,
[planHandle]: getFeaturesForPlan(
planHandleToMonthly[planHandle],
is4kEnabled,
exportFlow
),
}),
{}
);
return allPlanFeatures as Record<ExtensivePlanHandle, string[]>;
These do end up with the desired effect at the end of the day, but I'd rather be able to not have this partially working middle
You can try this:
const allPlanFeatures: Record<ExtensivePlanHandle, string[]> = {} as Record<ExtensivePlanHandle, string[]>;
this is not perfect, but sometimes you need to tell typescript compiler what is right.