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

The hover effect in CSS brings life to list items when filled with content

I am attempting to create an animation for an <li> element that gives the illusion of a fill effect moving from left to right when hovered over. This is my current progress: ul { list-style-type: none; } .hoverTest { float: left; margin-right: 1 ...

Incorporating yarn into your Vue3 project with Typescript

I'm attempting to implement a solution from https://yarnpkg.com/package/vue-disable-autocomplete that disables autocomplete in my Vue3 project. After running yarn add vue-disable-autocomplete, I included the following code: import DisableAutocomplete ...

Can you please explain how to switch the focused slide by clicking on a specific slide in swiper.js?

When using swiper in centeredSlides mode with the loop option set to true, I want a clicked slide to become the centered slide in the swiper carousel. Swiper provides me with the index of the clicked slide, but how can I use it to change the centered slide ...

Maintain a fixed element and enable the rest of the elements to scroll as the mobile browser address bar collapses while scrolling upwards

Currently facing a challenge where I want the background image to remain static while the address bar and content underneath scroll up. The image occupies 90% of the view height, and although I've prevented it from resizing and jumping when the addres ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

Storing the selected radio button value in AsyncStorage using React Native: A step-by-step guide

Can anyone help me with storing the users selected radio button value in AsyncStorage? I have radio button values being retrieved from another file and assigned to labels. Here is an example of how my radio buttons are structured: import RadioButtonRN fr ...

Encountering issues with installing Angular using npm due to errors

When I run npm install, I encounter errors. Though I can get it to work by using npm install --force, I prefer not to rely on the force flag. After reading through the errors, it seems like there might be a version compatibility issue, but I'm having ...

Concatenating Arrays in nodeJS

Here's a code snippet that deals with arrays: const array = [ "apple", "banana", "cherry" ]; I'm trying to create a multiline string like this: const foo = " apple banana cherry "; Is there a way for me to begin a new line with each it ...

HTML list with clickable elements for querying the database and displaying the results in a <div> element

Patience please; I am a newcomer to StackOverflow and this is my inaugural question. Struggling with writing an effective algorithm, I wonder if my attempts to "push" it forward are causing me to complicate what should be a straightforward concept, or if i ...

Bootstrap-vue throws an error when Vue is not defined

Recently, I integrated bootstrap-vue into my Vue.js project by running the command yarn add bootstrap-vue bootstrap axios. Here is a snippet of my code: https://i.stack.imgur.com/oTBxn.png Another part of the code can be found here: https://i.stack.imgur ...

The process of embedding variables within a JSON Array function in JavaScript

As a newcomer to JavaScript, I am facing an issue while trying to create a simple program. I am attempting to store the variables 'name', 'document', and 'code' inside the JSON array called 'records'. var records = ...

What is the best way to update or reload an embedded application/pdf?

I have implemented an embed code using application/pdf in order to display a pdf document on the website. To dynamically change the src attribute of the embed when a link is clicked, I utilized javascript. I confirmed this action by displaying alerts to e ...

Update the VueJS application by loading and replacing the existing JSON data with new information

Is there a way to dynamically re-render the entire v-for loop and DOM after fetching and loading new JSON data to replace the current one? I want to be able to click on different options and have the products updated. Vue.use(VueResource); var produ ...

Having trouble establishing a connection between VueJS 3 and Socket.io

I am new to the world of Socket.IO and backend technologies. Although I have experience with Vue, I am currently facing a challenge in creating a basic multiplayer game. My stumbling block lies in connecting vueJS with SocketIO for my project. Here is th ...

The Safari keyboard navigation feature suddenly disappeared after uploading to Google App Engine

My current website is built using Vue.js (2.x) and deployed on Google App Engine. After testing the deployed application in Safari, I noticed that the accessibility feature "'skip navigation' on :focus" was no longer functioning proper ...

What is the best way to transfer information from a layout to its children within the app directory of Next.js?

One scenario I encounter frequently is the need for a button in a layout to toggle something within the components it contains. For instance, you might have a notifications button in a fixed layout that triggers a side panel to open in the main application ...

Storing a string in localStorage versus $localStorage in Angular 1 yields distinct value differences

I have encountered an issue in my angular controller where I am trying to save a token returned from an API endpoint as a string. In this example, I have used the variable testData instead of the actual token. var testData = "testdata" $localStorage[&apo ...

Remove objects from an array if they share identical key values

I'm having trouble getting this to work. I have an array of objects that looks like this: let myCities = [ { value: 'Barcelona', code: 02342837492482347 }, { value: 'Rome', code: 28282716171819 }, { v ...

Refreshing the page causes the Angular/Ionic Singleton instance to be destroyed

I have a TypeScript singleton class that is responsible for storing the login credentials of a user. When I set these credentials on the login page and navigate to the next page using Angular Router.navigate (without passing any parameters), everything wor ...