Guide to creating an object using a loop in typescript without relying on `Partial` to assign keys from a list

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.

Answer №1

Give this a shot:

const planFeaturesMap: Record<PlanType, Array<string>> = {} as Record<PlanType, Array<string>>;

It may not be flawless, but occasionally you have to guide the typescript compiler in the right direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating three functions with the same name, one with a callback, another with a promise, and the third with async/await, can

I am looking to create a versatile function that can be used in 3 different ways to handle npm dependencies Using Promises Using callbacks Using async/await For Instance 1) Using async/await var mongoose = require('mongoose'); async fu ...

Where can I find the HTML code I just inserted?

Why isn't the newly added jQuery code visible when inspecting the view-source after the jQuery trigger? The script below adds a simple alert-info paragraph (refer to the image) when the password is incorrect. See how the page appears after the code ...

Altering icons using timeouts in a repeating sequence

So, I have this code that is supposed to loop through each record in a table and change the save icon to a checkmark for 2 seconds before changing it back. However, it's not working as expected. I've used a similar method for other buttons which ...

The completion action is never carried out

I am currently facing an issue with one of my JavaScript functions. I have several $.ajax calls throughout my webpage followed by .done(), and they all seem to be functioning properly, except for one. Can anyone identify what could be causing the error? m ...

Check if the number field in the If statement is empty or contains an excessive number of decimal places, while excluding cases where only zeroes are present in the decimal places

I am currently working with the following line of code: if ($val === "" || ($val.split(".")[1] || "").length > 2) With some assistance from the helpful individuals here, I have managed to implement this code successfully. ...

Using object bracket notation in TypeScript to retrieve values from props with the help of string interpolation

I encountered an issue in my code while attempting to utilize a variable within my TSX component. This problem arises due to the dynamic props being passed into the component, which are always a string that matches one of four keys in the "characters" obje ...

Removing particular <li> elements with JavaScript

It appears that the function is unable to delete the Node containing the specified value unless it is the first value (such as 'apples'). Additionally, the for loop needs to run twice before any deletion occurs. What could be causing this behavio ...

The div containing the AJAX POST success message suddenly vanishes within moments of being uploaded

Encountering an issue following a successful AJAX post, where the updated div disappears shortly after Here are the jquery/PHP/POST data in sequence. Button On Click Function: function Delete_ID(clickBtnValue,clickBtnID,clickBtnName) { var my_data = {& ...

Tips for importing in VScode without including an index at the end of the URL

I'm attempting to set up vs-code so it can identify and propose imports without the need for an index file. foo (folder) - index (js file) current behavior: import './foo/index' expected behavior: import './foo' I've tri ...

Stop the stream coming from getUserMedia

After successfully channeling the stream from getUserMedia to a <video> element on the HTML page, I am able to view the video in that element. However, I have encountered an issue where if I pause the video using the controls on the video element a ...

Step-by-step guide on redirecting a page using AJAX while also sending data to a controller

Is it possible to redirect to another page after a successful action, but not able to retrieve the data that was passed? Here is the jQuery code: $.ajax({ type:'GET', url:link, data:data, success:functio ...

What other alternative is there besides sending the prop to the parent component?

Currently, I am facing a situation where I need to utilize the state from one component as a dependency value in the useEffect hook of another component. To provide a clearer understanding of this scenario, please refer to the image linked below. https:// ...

Can you explain the contrast between window.performance and PerformanceObserver?

As I delve into exploring the performance APIs, I have come across window.performance and PerformanceObserver. These two functionalities seem to serve similar purposes. For instance, if I need to obtain the FCP time, I can retrieve it from performance.getE ...

md-list-item containing md-radio-button

Trying to tackle this particular issue: https://github.com/angular/material2/issues/1518 I want the ability to click anywhere on the line of my md-item and have it trigger the radio-button action. settings.component.html : <md-radio-group [(ngModel) ...

After sending an HTML Gmail using Nodemailer, some rules may be missing from the CSS

I am attempting to send HTML content via Nodemailer to my Gmail account. Initially, I sent the email as plain text to ensure everything was working properly. const email = { from: emailAddress, to: sendTo, subject: ...

Running a Neo4j Cypher query with the help of jQuery

I've been attempting to create an Ajax call using jQuery to a Neo4j Server, both residing on the same machine. However, I keep encountering errors in the response. This is how my ajax call is written: var request = $.ajax({ type: "POST", url ...

eliminating identical items in an array

I've been working on finding and removing duplicate objects in an array, but I keep encountering an error when trying to access the filterList[i+1].tagID element. Strangely, manually inputting the [i+1] values seems to yield the correct results. I&apo ...

Creating a three-dimensional model of planet Earth using particles and Three.js technology

I'm attempting to recreate a similar effect found at , but with a twist. Instead of just particles, I want them arranged in a way that resembles the Earth - like a textured face. After examining their code, here is how they set up the particles group ...

I'm having trouble accessing my POST data using console.log. Instead of getting the expected data, all I see in the console when I try to GET is "

My code for the POST function is working, but when I try to retrieve and display the POST response from the server, all I get is "null". Can anyone help me figure out how to properly send data from my form to the server and then successfully console log it ...

Steps for deactivating a button based on the list's size

I am trying to implement a feature where the user can select only one tag. Once the user has added a tag to the list, I want the button to be disabled. My approach was to disable the button if the length of the list is greater than 0, but it doesn't s ...