What is the best way to dynamically add a new item to an object in Typescript?

var nodeRefMap = {};
function addNodeRef(key: String, item: Object){
       console.log("Before:");
       console.log(nodeRefMap);
       nodeRefMap = Object.assign({key: item}, nodeRefMap);
       console.log("After:");
       console.log(nodeRefMap);
}
addNodeRef("123",{});
addNodeRef("345",{});

I am encountering an issue while trying to add a new parameter using the function above in Typescript. The problem lies in setting up the key of the object. The desired output should be:

{
   "123": {},
   "345": {},
}

However, the current result is:

{
   "key": {},
}

What modifications do I need to apply in order to achieve the expected outcome?

Answer №1

Your code has a critical issue where you are not passing the correct type of string as an argument. It is recommended to update your function's input parameters from (key: String, item: Object) to (key: string, item: object). By doing so, you explicitly define the data types for your input arguments. Additionally, when assigning a value to nodeRefMap, it is preferable to use the syntax like

nodeRefMap = Object.assign({}, {[key]: item});
.

The revised code below demonstrates the appropriate usage:

let nodeRefMap:{[key: string]: object};
function addNodeRef(key: string, item: object){
       console.log("Before:");
       console.log(nodeRefMap);
       nodeRefMap = Object.assign({}, {[key]: item});
       console.log("After:");
       console.log(nodeRefMap);
}
addNodeRef("123",{"a":1});
addNodeRef("345",{"b":2});

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

Having trouble creating two bar charts with different data sets in ng2-charts using Angular 8

I attempted to display two charts simultaneously on a single page by utilizing the following code in HTTP: <div class="chk-block-content"> <canvas height="100" width="500" baseChart [datasets]="barChartData" [labels]="barChartLabels" [options ...

Navigate using an abstract data type

I am looking to transmit abstract data (In Angular 4 or 5) from one component to another without it being visible in the url. Currently, I am using the following method: let navigationExtras: NavigationExtras = { queryParams: { "firstname": "Nic ...

Unable to utilize the useState hook in TypeScript (Error: 'useState' is not recognized)

Can you identify the issue with the following code? I am receiving a warning from TypeScript when using useState import * as React, { useState } from 'react' const useForm = (callback: any | undefined) => { const [inputs, setInputs] = useS ...

Having trouble importing a variable from a precompiled library in TypeScript JavaScript

Here is the content of my package.json file: { "name": "deep-playground-prototype", "version": "2016.3.10", "description": "", "private": true, "scripts": { "clean": "rimraf dist", "start": "npm run serve-watch", "prep": "browserify ...

What steps can I take to ensure TypeScript compiler approves of variance in calling generic handlers, such as those used in expressJS middleware?

disclaimer: I am a bit uncertain about variance in general... Here is the scenario I am facing: // index.ts import express from 'express'; import {Request, Response} from 'express'; const app = express(); app.use(handler); interface ...

Using Typescript in NextJS 13 application router, implement asynchronous fetching with async/await

Recently, I implemented a fetch feature using TypeScript for my NextJS 13 project. As I am still getting familiar with TypeScript, I wanted to double-check if my approach is correct and if there are any potential oversights. Here is the code snippet from ...

Output in Typescript for the chosen option

A message can be sent based on the user's choice of either Now or Later. If the user selects Now, the message will be sent immediately. If Later is chosen, a date format option needs to be created for setting a future date. <label for=""& ...

The parameter "disabled=false" is not functioning properly in TypeScript 2.1

Struggling to deactivate a field by accessing the element ID in TypeScript 2.1. Came across this syntax for TypeScript 1.5, but unfortunately, it doesn't seem to work in 2.1. Any assistance would be greatly appreciated. ( document.getElementById(&apo ...

Is every export automatically bundled as default by typescript?

import * as mongoModule from 'mongodb'; The code snippet above demonstrates the standard ES6 method of importing mongodb in Node.js. It is interesting to note that while using import mongodbModule from 'mongodb' is expected to result i ...

Ensuring a child element fills the height of its parent container in React Material-UI

Currently, I am in the process of constructing a React Dashboard using MUI. The layout consists of an AppBar, a drawer, and a content area contained within a box (Please correct me if this approach is incorrect)... https://i.stack.imgur.com/jeJBO.png Unf ...

Relaying numerous references in TypeScript

Having some trouble forwarding an object of refs in TypeScript and struggling with how to properly type them. Here are the refs and the way I'm passing them into my component. const storyRef = useRef<HTMLElement>(null); const parcoursRef = useR ...

Utilizing PrimeNG dropdowns within various p-tree nodes: Distinguishing between selected choices

I am working with a PrimeNg p-tree component <p-tree [value]="treeNodes" selectionMode="single" [(selection)]="selectedNode"></p-tree> The treeNodes are defined using ng-templates, with one template looking li ...

The constructor in a Typescript Angular controller fails to run

Once the following line of code is executed cockpit.controller('shell', shellCtrl); within my primary module, the shell controller gets registered with the Angular application's _invokeQueue. However, for some reason, the code inside t ...

What specific event do I require for the onChange event in React using TypeScript?

I'm facing a problem while working with React TypeScript. I need to type the onChange event for a select element, but the data is coming from event.value instead of event.target.value. What should be the appropriate event to use in this case? Below i ...

Why doesn't Typescript 5.0.3 throw an error for incompatible generic parameters in these types?

------------- Prompt and background (Not crucial for understanding the question)---------------- In my TypeScript application, I work with objects that have references to other objects. These references can be either filled or empty, as illustrated below: ...

Unable to locate dependencies while testing the react package locally

Recently, I came across this npm package designed for React using Typescript. To debug it locally, I initiated npm link in a new React project but encountered an error: https://i.sstatic.net/nObH6.png I suspect it may not be reading the packages correct ...

There are no HTTP methods available in the specified file path. Make sure to export a distinct named export for each HTTP method

Every time I attempt to run any code, I encounter the following error message: No HTTP methods exported in 'file path'. Export a named export for each HTTP method. Below is the content of my route.ts file: import type { NextApiRequest, NextApi ...

Determine the Variable Type by Evaluating the Value of Another Variable

I am looking to implement the following functionality: document("post").insert({ ... } /* TYPE SHOULD BE AUTOMATICALLY DETERMINED BY TYPESCRIPT */ ); The document() function returns an object that includes methods like insert. The returned objec ...

Tips on using Visual Studio Code to troubleshoot Angular 4 unit tests

I am working on an Angular 4 project with Material design in Visual Studio Code. The setup is done using angular/cli. Currently, I have been writing unit tests using Karma and Jasmine. However, when trying to debug the tests by setting breakpoints, it doe ...

Error: Issue determining the type of variable. Unable to eliminate type 'any'

I am trying to load some widgets from a template object (possibly JSON in the future). Here's an example: type RectangleTemplate = { name: 'Rectangle'; props: { width: number; height: number; } }; type ButtonTemplate = { nam ...