Introduction
I am currently facing a challenge with initializing an object with predefined keys. The issue arises when I try to start with an empty object {} as it interferes with my typing.
The Issue:
I have a set of values that I want to use as keys and initialize an object using those keys. In Python, I would typically achieve this by:
myDict = {key: value for (key, value) in zip(myKeys, [[]]*len(myKeys))}
This is intended to give the type of Record<myKeys, string[]>
.
In TypeScript, I encountered difficulties as I needed to first initialize the object with an empty list before populating it with keys/values. I aim to avoid converting it into the correct type after defining it initially.
Approaches Tried:
I attempted the following solutions:
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[]>;
While these approaches eventually lead to the desired outcome, I prefer not to have this intermediate partially working solution.