Required attributes not found for data type in TypeScript

When the following code snippet is executed:

@Mutation
remove_bought_products(productsToBeRemoved: Array<I.Product>) {

    const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine);
    const reducedProductsInVendingMachine: Array<I.Product> =
        tmpProductsInVendingMachine.reduce((tmpProductsInVendingMachine, { id, ...rest }) => ({ ...tmpProductsInVendingMachine, ...{ [id]: { id, ...rest } } }), {});
    productsToBeRemoved.forEach(({ id }) => reducedProductsInVendingMachine[id].productQty--);
...

An error message is produced:

TS2740: Type '{}' is missing the following properties from type 'Product[]': length, pop, 
push, concat, and 28 more.
250 |
251 |         const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine);
> 252 |         const reducedProductsInVendingMachine: Array<I.Product> =
    |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
253 |             tmpProductsInVendingMachine.reduce((tmpProductsInVendingMachine, { id, ...rest }) => ({ ...tmpProductsInVendingMachine, ...{ [id]: { id, ...rest } } }), {});
254 |         productsToBeRemoved.forEach(({ id }) => reducedProductsInVendingMachine[id].productQty--);

The question arises: What is the return type of the reducer function in this context?

The products being manipulated are structured as follows:

[{
    id: 1,
    productName: "coke",
    productPrice: 2, 
    productQty: 20
},
...
]

Answer №1

reducedProductsInVendingMachine is actually an Object, not an Array.

To resolve this issue, you can convert {} to the correct type when initializing the parameter in Array.prototype.reduce():

const reducedProductsInVendingMachine =
    tmpProductsInVendingMachine.reduce(
        (tmpProductsInVendingMachine, { id, ...rest }) =>
            ({ ...tmpProductsInVendingMachine, ...{ [id]: { id, ...rest } } }),
        {} as { [key: I.Product['id']]: I.Product }
    );

When implemented like this, the code compiles successfully and the variable reducedProductsInVendingMachine is inferred correctly as

{ [key: I.Product['id']]: I.Product }
(with I.Product['id'] resolved accordingly).

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

Achieve seamless integration of PHP function execution with Javascript onClick without the need for page

After delving into my research, it seems like Ajax and/or JQuery may be the way to go for what I'm trying to achieve. However, I wanted to double-check before moving forward in that direction. The task at hand involves using a javascript onclick func ...

Switch from buffer to base64 encoding for viewing in Angular

Hello, I have developed an application using the MEAN stack. Currently, I am facing an issue with retrieving images from my endpoint. The image array values that I am receiving look like this: 8,8,7,7,9,8,9,8,9,8,9,9,8,8,8,8,7,9,7,7,9,10,16,13,8,8,16,9,7, ...

Is there a way to trigger an AJAX request right before I leave the page or unload it?

When the window is about to be unloaded, an AJAX request is sent to a specific URL including the recent tracking ID and the time spent on the page in seconds. However, the behavior I am experiencing is an alert displaying [object Object]. ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

Steps to configure caching settings to ensure no caching for the entire site during specific hours, and constant no-cache policy for a particular page

Managing cache for my website has become quite the challenge. Some pages need to be cached during certain hours to improve navigation speed, while others must not be cached during crucial data update times. And to add to the complexity, there are pages tha ...

What is an alternative way to retrieve the page title when the document.title is unavailable?

Is there a way to retrieve the page title when document.title is not available? The code below seems to be the alternative: <title ng-bind="page.title()" class="ng-binding"></title> How can I use JavaScript to obtain the page title? ...

Ways to convert a string into a Date object without using moment.js

I am facing a challenge with 2 dates that are stored in the following format: "04.12.2019, 09:35" // Today "05.12.2019, 12:50" // Another date I need to compare these dates to determine if they have passed or are yet to come. My initial approach was to ...

How do I connect to a different application's view?

When working with a view that has tiles, I am looking to click on one of them and be directed to a different application that I have created. In typical cases, I would specify the view folder for navigation. However, when attempting something similar for ...

JavaScript inserted into debug console by developer

Is there a method to troubleshoot code that has been added through the firefox developer console terminal? For example, I added document.onkeydown = function(event) { // code logic for checking keys pressed } If only I could determine which .js file t ...

Utilizing JavaScript to implement conditional if-else statements on CSS properties

I am trying to implement conditions on CSS properties in JavaScript. What is the most efficient approach to achieve this? <html> <head> <title>TOOLTIP USING JAVASCRIPT</title> <style> span{ curso ...

Automate your workflow with Apps Script: Save time by appending a row and seamlessly including additional details to the

I currently have 2 server-side scripts that handle data from an html form. The first script saves user input to the last row available in my Google sheet, while the second script adds additional details to the newly created row. Although both scripts work ...

Utilize Jquery to dynamically update form input in real time based on checkbox selections

I am working on a form that requires real-time calculation of GST (Goods and Services Tax) directly within the form (GST = Price/11) This functionality has been implemented with the following script. Additionally, the calculation needs to be adjust ...

Unable to change the value of selected items in checkbox event within a React context

Today marks the beginning of my journey into developing a React application. I am currently faced with the challenge of retrieving the row ID of a checked checkbox in a React table. Utilizing hooks, I have managed to transfer the states to another compone ...

Troubles arise when attempting to bind or watch a service variable that is shared between two

I'm really struggling to understand what's happening here. I grasp the basics of Angular's $digest cycle, and according to this Stack Overflow post, I seem to be correctly assigning a scoped variable to a service's property (an array in ...

Develop a JSON parsing function for VUE reusability

Currently, I am iterating through an array in Vue that contains objects with strings nested within. These objects have various properties such as idType, type, user, visibility, seller, product, company, and additionalData. notifications: [ 0: { idTy ...

How can I assign a value other than a string to a placeholder or vue property?

As I develop a content management system using Nuxt and Pug/Jade, I am looking for an efficient way to create a list of input fields for users to enter information. My idea is to use the v-for directive to render the list and dynamically set the value and ...

Error in React Native Typescript: The type 'string' cannot be assigned to the type '"solid" | "clear" | "outline"'. (Error code: ts(2322))

I have integrated TypeScript with React Native in my project. import React from 'react'; import { Button } from 'react-native-elements'; import { IThemedButton } from '../../../models/themedButton'; interface IThemedButtonPr ...

Double Tap Required to Update AngularJS Scope

Controller: // Modal Controller app.controller("ModalCtrl", ["$scope", "$filter", function($scope, $filter) { var date = new Date(); var currentDate = $filter('date')(new Date(), 'MM/dd/yyyy'); // Form Submit Actions $scope.s ...

Ensuring radio button validation prior to redirecting to contact form

I created a survey form using HTML and CSS. I am looking to add validation to the questions before redirecting to the Contact form page. Currently, when a user clicks on the submit button in the Survey form, the page redirects to the contact form. Howeve ...

Having trouble populating and submitting a selected option from a dropdown menu in Angular?

Upon loading the page, the Category dropdown automatically populates with data from the database. However, when I attempt to select a value from the dropdown and click a button to post the data to a specified URL, an error occurs: ERROR Error: Error tryin ...