Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
How to use a loop to create an object with keys from a list in typescript without using `Partial`?

Overview

Im trying to create an initialise an object with known keys, however the initial empty object {} that I need breaks my typing.

The problem:

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.

what ive tried:

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!