Creating an object in JavaScript using an array type初始化数组类型为对象javascript

In my code, there is an interface defined as Products

 export interface Products{
    category: string;
    imageUrl: string;
    price: number;
    title: string;
 }

Within my component, I have a variable named products which is an array of type Products

products: Products[];

I am currently attempting to map the response from my service to the products variable, but I encounter an error stating Type

'{}[]' is not assignable to type 'Products[]'

The cause of this error is unclear to me at the moment

this.subscription = this.productService
  .getAll()
  .subscribe(
    products =>
      (this.products = products.map(p => ({ ...(p.payload.val() as {}) }))),
  )

Answer №1

When looking at this assignment clause:

this.products = products.map(p => ({
  ...(p.payload.val() as {})
}))

The code is casting p.payload.val() to type {} and then spreading it into an empty object, which effectively clones it while maintaining the type as {}. Consequently, products.map(...) results in a type of {}[], also known as Array<{}>. Given that this.products is a collection of Product[], there exists a type incompatibility.

If p.payload.val() already possesses a type of Product, there is no necessity for any casting:

this.products = products.map(p => p.payload.val())

// or if you require the cloning functionality...

this.products = products.map(p => ({ ...p.payload.val() }))

If p.payload.val() does not have the type Product, the correct move would be to cast it directly to Product instead of {}:

this.products = products.map(p => p.payload.val() as Product)

// alternatively, for cloning purposes...

this.products = products.map(p => {
  return { ...p.payload.val() } as Product
});

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

How can these lines be drawn in a simple manner?

I have been using the div tag to create a line, but I'm looking for an easier solution. If you have another method in mind, please share it with me. #line{ background-color:black; height:1px; width:50px; margin-top:50px; margin-left:50px; f ...

403 Forbidden error encountered while making a REST API call using jQuery AJAX

Attempting to create a basic jQuery ajax call to an API Here is the code I'm using: jQuery.ajax({ type: "GET", url: "http://example.com/api/v1/testapi", headers: { "Authorization": "Basic Ylc5aWXXXXXXlk1ucWx5ZnA=" }, success: fu ...

Internet Explorer 11 is not interested in giving attention to a disabled element

I'm trying to limit text input to only one of two fields. My approach involves checking the value of a field when it loses focus, and then disabling the other field if the initial one is not empty. Below is an example: HTML: <div class="contain ...

A guide on logging errors triggered within reducers

I'm facing a challenge in Redux where I am unable to get error messages logged to the console. My stack includes React, Redux Toolkit, and TypeScript. Here is a snippet of one of the reducers I've implemented: // Reducer const removeResourceRedu ...

Does Vuejs have a counterpart to LINQ?

As a newcomer to javascript, I am wondering if Vue has an equivalent to LinQ. My objective is to perform the following operation: this.selection = this.clientsComplete.Where( c => c.id == eventArgs.sender.id); This action would be on a collect ...

What is the best way to merge two different types in TypeScript?

JavaScript is struggling to merge two objects with identical properties. During development, there's a need to combine two configurations. if (mode === 'development') { return merge(productionConfig, Configuration); } The interfaces ...

Trying to work through solving the issue of accessing document.frames["someframe"].function in Chrome instead of IE

I am encountering an issue with my code that is working in Internet Explorer but not in Chrome. try { top.document.frames["myFrame"].compare(); } catch(err) { alert("This is not executed."); } Any suggestions on how to resolve this compatibility pr ...

Tricks for refreshing cached web page assets in the year 2023

So far, here are some of the old Cache Buster techniques I've come across: Adding a query string in the link src: /mstylesheet.css?cache_buster=12345 Changing the filename each time: /mstylesheet-12345.css Using Apache with Cache-Control "must-revali ...

Linking input to radio buttons in Vue.js

When creating an edit form page, I encountered an issue where the page was not loading properly. Before the page loaded, I ran the following code: beforeMount(){ if(this.$route.meta.mode === 'edit'){ this.initialize = '/api/arti ...

Yet another method for transferring arguments in typescript

I have a TypeScript class with a method that takes three arguments. class MyClass { public static carStatus(name : string , color : string , isReady : boolean){ let result = isReady ? 'is ready' : 'is not ready'; return `${co ...

What is the best way to loop through properties of a Typescript interface?

I am currently working with an interface called FilterData, which has the following structure: export interface FilterData { variables?: string[]; processDefinitionKey?: string; } When I make a request to the server, I receive an object named filterS ...

Scrollbar in an HTML selection tag

Is there a way to add a scroll bar to an HTML select box without using JavaScript? Alternatively, is there a JavaScript library that can achieve this behavior? Also, I'm looking for a redesign of the interface where I have two select boxes and items ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

Utilizing TypeScript Variables within a Jquery Each Iteration

I have a variable named tableIndexNumber that I need to use in different methods. When trying to access this variable, I use "this.tableIndexNumber" and it works fine. However, I face an issue when using it inside a jQuery each loop because the HTML elemen ...

AngularJS Routing misinterprets hash href from jQuery UI Datepicker

This issue is a result of my own oversight. I neglected to properly initialize the model for the datepicker, causing jQuery UI to prevent the navigation event from firing. If you're encountering this same problem, chances are there's another mist ...

Navigate to the initial error on a form submission in a Reactjs application containing numerous form fields

I am working on a project using React along with Material UI and TypeScript, where I have implemented a form. Upon form submission, if there are validation errors in any input fields, I would like the page to automatically scroll to the first input field w ...

Style selector for dynamic drop-down menus

import React, { Component } from "react"; export default class FontChanger extends Component{ constructor(props){ super(props); this.state ={ selectedFont: "", currentFont: "", }; this.handleFon ...

The onchange event in the dropdown activates a function, however, there is no alteration observed in the three

I am attempting to create a dynamic display of a green or brown floor on a webpage using three.js, based on the selection from a dropdown list. However, I am encountering an issue where the floor images do not update even though the function is being execu ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

Is it possible to detect a swipe event without relying on third-party libraries

Is there a way to detect a swipe instead of a click using only pure jQuery, without relying on jQuery Mobile or external libraries? I've been examining the TouchSwipe source code, but it contains a lot of unnecessary code for what I really need - sim ...