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

I have discovered some amazing jQuery image hover effects that are simply breathtaking –

I have been using the Adipoli jQuery Image Hover Effects plugin, but I am facing issues with changing certain properties. The image is set to change to grayscale initially and then switch to color on hover. However, when I click on the image, it should mai ...

Enhancing the appearance of a checkbox within a ReactJS setting

I'm having trouble customizing a checkbox in a ReactJS environment for IE11. I've tried various approaches, but nothing seems to work. Can anyone offer any advice? Here is the code snippet: CSS: .squared { input[type=checkbox] { bo ...

Challenges associated with utilizing img src in JavaScript

I am facing a simple issue. I have carInfo data retrieved from a JSON file, but I am struggling to correctly parse the img source stored in the variable $imgsrc instead of treating it as a string called "$imgsrc". This data needs to be appended to my HTML ...

How can I attach events to newly generated elements without using jQuery?

If I want to dynamically add a form to my webpage (through AJAX or other JavaScript methods), how can I attach event listeners to these elements before they actually exist on the page? When using jQuery, it's simple to bind the events to a parent ele ...

What are the drawbacks of introducing a dependency within the constructor?

I'm struggling to understand why breaking the rules is considered bad. import {DepClass} from './di-import' // <- some dependency imports here class DI1 { dep1: DepClass constructor(){ this.dep1 = new DepClass() // ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

Error in React+Redux: Trying to access the "address" property of a null value is not permitted

I am new to using react and encountering an issue with my ecommerce app. The app runs smoothly until I log out and then log back in at the shipping address page, which triggers the following error: TypeError: Cannot read property 'address' of nu ...

What are the best ways to resolve the warning from webpack in Express?

I have set up webpack to bundle both the server and client side code... Below is my webpack configuration: const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin&a ...

Steps to retrieve the value stored in a variable within an Angular service from a separate component

How can I effectively share question details and an array of options from one component to another using services? What is the recommended method for storing and retrieving these values from the service? In my question-service class: private static ques ...

My goal is to generate four HTML buttons that trigger specific functions: addition, subtraction, multiplication, and division

I am currently learning JavaScript, and I am facing some challenges with my assignment. The task is to create four buttons in HTML that trigger different functions - addition, subtraction, multiplication, and division. The goal is for the user to input two ...

What is the method for arranging objects in AngularJS using a custom sorting sequence?

I would like to display an array of object's properties in a custom sorted order. Here is the initial array: $scope.weekDays = [ { "day" : "TUESDAY", "count": 10 }, { ...

What is the best way to limit a form to only allow 2 checkbox selections?

Seeking advice on implementing a form for a website giveaway featuring 3 prizes. Each participant should only be able to select 2 items from the list. I've already created a JavaScript-based form, but I'm concerned about its reliability since it ...

Troubleshooting loading specific story types on hacker news API with Angular.js

I have been working on a hacker news client using the official hacker news firebase API and Angular.js. Everything seems to be working fine except for the 'jobstories' posts, which are not rendering on the screen even though the story IDs are bei ...

Ensure the button remains in focus after clicking on the input field: Material-Ui

I'm currently working with a material-ui dialog and I've encountered an issue. When I click on the input field, the social button loses focus which is not what I want. Here's how it looks: Here's the desired behavior where the social b ...

Tips for customizing the border radius style of the menu in Vuetify's v-autocomplete component

I am looking to customize the appearance of the drop-down list in the v-autocomplete component by adding a border-radius style, as depicted in the image below. The current design I have achieved closely resembles the visual shown below. Previously, I app ...

Creating a class in JavaScript following an AJAX request

After receiving an AJAX response, the class "navtex-message" doesn't work properly when I create HTML with JavaScript. function formatNtxMessage( m ) { return '<div class="row">' + '<div class="col-lg-9">' ...

The map fails to load on the HTML page

I am struggling to load a map into my HTML page from a file located in the app folder. Despite using the correct code for inserting the map, it still does not load properly. <!-- Contact section start --> <div id="contact" class="contact"> ...

Illuminated Box with Text Beneath Image Overlay

Is there a way to customize the text displayed under each zoomed-in image even further, using images, etc. instead of just relying on the alt text? An ideal solution would involve displaying the text in a div. You can find the codepen here: // Looking ...

I'm curious about the outcomes of the JavaScript test. Could someone provide an explanation

Recently, I was in the process of writing a blog post discussing the importance of checking for the existence of jQuery elements before attaching event handlers. To illustrate this, I quickly created a jsfiddle example here. What puzzles me is that the re ...

Using MUI Select with Array of Objects for values - Learn how to deselect a predefined state

I have a list of objects structured like this: [ { _id: "6311c197ec3dc8c083d6b632", name: "Safety" }, ........ ]; These objects are loaded as Menu Items options for my Select component: {categoryData && c ...