To avoid TS2556 error in TypeScript, make sure that a spread argument is either in a tuple type or is passed to a rest parameter, especially when using

So I'm working with this function:

export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) {
  // Beginning point:
  //  [key1,key2,key3],
  //  [value1,value2,value3]
  //
  // End point: {
  //  key1: value1,
  //  key2: value2,
  //  key3: value3
  // }

  if (keyArr.length === valueArr.length) {
    // @ts-ignore
    return Object.assign(...keyArr.map((el,index) => ({[el]: valueArr[index]})))
  } else {
    throw new Error(`The arrays must be the same length: ${{keyArr}}, ${{valueArr}}`)
  }
}

I am trying to achieve the desired result from the example above - End point. I attempted to assign it to a variable, but encountered the same issue.

I also tried replacing it with:

Object.assign({...keyArr.map((el,index) => ({[el]: valueArr[index]}))})

However, the outcome would be:

{0: {key1: value1}, 1: {key2: value2}}

The same goes for

Object.assign([...keyArr.map((el,index) => ({[el]: valueArr[index]}))])

Resulting in: [{key1: value1}, {key2: value2}]

Answer №1

When utilizing the Object.assign method, it is crucial to ensure that at least one parameter is specified. In your particular function, there was a possibility that the array being spread could be empty. The key message in the error points out that ""must be passed to a rest parameter" which indicates the need to utilize the correct overload signature from the various overload signatures. To avoid the necessity for // @ts-ignore, the recommended approach would be:

return Object.assign({}, ...keyArr.map((el,index) => ({[el]: valueArr[index]})))
//                   ^^^

(Playground demo)

However, an even better alternative to using Object.assign is Object.fromEntries, specifically designed for handling iterables of tuples:

export default function getObjectFromTwoArrays(keyArr: Array<any>, valueArr: Array<any>) {
  if (keyArr.length === valueArr.length) {
    return Object.fromEntries(keyArr.map((key, index) => [key, valueArr[index]]))
  } else {
    throw new Error(`Arrays should be the same length: ${{keyArr}}, ${{valueArr}}`)
  }
}

Answer №2

It appears that you are attempting to transform an array of keys and an array of values into an object based on the parameter names used. However, Object.assign requires two parameters: a source and a target, neither of which should be arrays. To achieve your desired outcome, you should utilize Object.fromEntries after combining the key and value arrays into pairs:

const combineArrays = (keys, values) => {
  if (keys.length === values.length) {
    return keys.map((key, index) => [key, values[index]]);
  } else {
    throw new Error('Arrays must be equal in length for merging');
  }
};

const createObjectFromArrays = (keys, values) => Object.fromEntries(combineArrays(keys, values));

The Object.fromEntries function transforms an array of key/value pairs into an object, serving as the opposite of Object.entries. For more information, refer to:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

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

Refresh the image source using the AJAX success callback

Previously, I was updating Label values within the AJAX success function as shown below. Now, I am looking for a way to use the same method to change or update the "src" attribute of an <img id="myimage" src=""/> $.ajax({ url: 'clmcontrol_l ...

How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file: "scripts": [ "node_modules/csspatternlibrary3/js/site ...

Date range within a conditional statement

I have encountered this code snippet: function auto_select_param_call_time() { if (today() == date("02.01.2017") || today() == date("03.01.2017")) { auto_click_param("call_time", "Non-working day"); } else { //Do something else ...

Issues are arising with the for loop in an express node js app using ejs, as it is not displaying the intended data and

I am currently utilizing a for loop in JavaScript to display all the users from the database using ejs. I have included the code snippet below. This is within an express/node js application where SQL is used for data storage. <div class = "Contacts ...

Guide on adjusting the CSS styling of elements in real-time from the backend using a user customization panel to modify the appearance of various web pages

Imagine a scenario where we have a website consisting of multiple pages, including a user account page. The user has the ability to modify the color, font size, and style of certain elements on other pages for their own viewing preferences. How can this fu ...

Avoid circular dependencies in Angular 6 to ensure proper association between modules

When working with TypeScript, how should I handle the scenario where Cat has an owner: Person Person owns a pet: Cat Cat import {Person} from './person' export class Cat { owner: Person constructor(){ this.owner = new Pers ...

Navigate to the chosen item in material-ui scroll bar

Currently, I have a list created using material-ui which contains numerous items and displays a scrollbar due to its size. I am looking for a way to automatically scroll to the selected item within the list. Does anyone have any suggestions on how I can a ...

Displaying dropdown options based on the previous selection made by the user

Can I link the data in my second dropdown to the selection made in the first dropdown? I tried a similar solution from stackoverflow without success. You can find the reference here. The code works when directly copied and pasted but not within my system. ...

The useEffect hook in React is signaling a missing dependency issue

Any tips on how to resolve warnings such as this one src\components\pages\badge\BadgeScreen.tsx Line 87:6: React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array react-hoo ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

A guide to creating a JavaScript function that outputs a script in string form

Currently, I am utilizing angular and seeking to add a script to my directive's template. My goal is to create a function that can take the necessary parameters for the script and return it as a string. This approach would prevent me from having to em ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

Keep an eye on the syncing progress of pouchdb replication

What is the best way to alert the user if there is a loss of Internet connection or if the server goes offline, causing live sync to stop? var localdb = new PouchDB('localdb'); var remotedb = new PouchDB('http://localhost:5984/xyz&a ...

Vue table does not update when checkbox is unchecked

I am currently utilizing Daisy UI and basic VUE to create a checkbox functionality. When I check the checkbox, it successfully filters the table entries; however, when I uncheck or check another checkbox, the filter does not refresh again. Below is my tab ...

Issue with Jquery .on() causing toggleClass function to not trigger

Adding a column dynamically to a table on click with JS/Jquery is achieved as demonstrated below $("#btn").click(function(){ $('#week_title').append('<th>Week '+count+'</th>'); count++; $('.tag&ap ...

Find out if a dynamically imported component has finished loading in Nextjs

Here is a simplified version of my current situation import React, { useState } from 'react'; import dynamic from 'next/dynamic'; const DynamicImportedComponent = dynamic(() => import('Foo/baz'), { ssr: false, loading ...

Encountering the error code 'ERR_EMPTY_RESPONSE' while utilizing an AJAX-powered live search feature

My website features a live AJAX search bar that retrieves records from a MySQL database. However, when users repeatedly conduct searches by modifying the search criteria, some web browsers display an error message stating 'ERR_EMPTY_RESPONSE'. ...

How can we determine the remaining balance in the user's wallet after making purchases using JavaScript?

There are three arrays containing data from the back-end, with unknown names or products. The task is to calculate the total amount spent by the user and how much money is left in their wallet. In case the user runs out of money, they can take a loan which ...

Error in Chart.jsx: Unable to retrieve the length property of an undefined object in the COVID-19 Tracker App

INQUIRY Greetings, I am in need of assistance to identify an error that is perplexing me. The source of this code can be traced back to a tutorial on creating a covid tracker available on YouTube. While attempting to implement the chart feature, I encounte ...

guide to utilizing npm/yarn with tsx react

I've recently made the switch to using TypeScript with React, but I'm encountering a problem. After installing certain packages from npm or yarn, I'm having trouble using them in my .tsx components. The error message suggests looking for @ty ...