The type CustomModel[] lacks the property 'XYZ' in it

Using TypeScript v2.7.2

Check out the code snippet below:

import { Component, OnInit } from '@angular/core';
import { Ingredient } from "../shared/ingredient.model";

@Component({
  selector: 'app-shopping-list',
  templateUrl: './shopping-list.component.html',
  styleUrls: ['./shopping-list.component.css']
})
export class ShoppingListComponent implements OnInit {
  ingredients : Ingredient[] = [
    new Ingredient('Apples', 5),
    new Ingredient('Tomatoes', 10)
  ];
}

The "shared" folder is within the "App" folder, one level above (../ in import). Here is what my Ingredient model looks like:

export class Ingredient {
  constructor(public name: string, public amount: number) {}
}

The JavaScript output of this code works fine, but when working with TypeScript I encounter an error that seems puzzling:

Error:(10, 3) TS2322:Type 'Ingredient[]' is not assignable to type 'Ingredient'. 
Property 'name' is missing in type 'Ingredient[]'.

Even though I specified an array containing elements of type Ingredient and initialized it correctly, why does TypeScript expect the array itself to have a 'name' property instead of assuming it as an array?

Why is there an error regarding the missing 'name' property, when it is clearly defined in the constructor parameter?

I'm unable to provide the source material of the Udemy course I was following for this exercise. The course continues without addressing this issue, probably because the code compiles and functions smoothly at this stage.

Edit: Included Angular tag for reference.

Answer №1

I've taken the liberty of incorporating your code into a fresh Angular project that I created. I organized everything neatly within a single file structured like this:

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent {
    private ingredients: Ingredient[] = [
        new Ingredient('test', 10),
        new Ingredient('test', 10)
    ];
    constructor() {
        this.ingredients.forEach(item => {
            console.log(item);
        });
    }
}

export class Ingredient {
    constructor(public name: string, public amount: number) { }
}

The implementation is running smoothly as intended. By checking the console, I can confirm that both elements of the array are being displayed correctly. I encourage you to give it a try by copying and pasting this code into your own project. It should function without any issues based on my testing. If needed, you can press f12 on the "Ingredient[]" identifier to verify that you are referencing the correct class. My apologies for not leaving this feedback as a comment, as my reputation level doesn't permit me to do so at the moment.

Answer №2

Upon reviewing your code, I've noticed a minor issue that needs attention. Could you consider updating the following line by adding either 'var' or 'let'

`let ingredients : Ingredient[] = [
        new Ingredient('Apples', 5),
        new Ingredient('Tomatoes', 10)
    ];`

I believe this adjustment could be beneficial.

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

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

A data type labeled as 'undefined' needs to include a method called '[Symbol.iterator]()' which will then return an iterator

I've been working on converting my reducer from JavaScript to TypeScript, but I keep encountering a strange error that I can't seem to resolve. The issue arises when I attempt to use ellipsis for array deconstruction in the reducer [...state.mess ...

Django Angular 403 Error: CSRF-cookie not accepted. Reason: CSRF token is missing or incorrect

Currently, I am working on developing a Single Page Application (SPA) with Angular6 integrated with Django. However, I am facing an issue where Django is not accepting the csrftoken cookie that I am sending along with my requests. In my settings.py file, I ...

How to include a cancel button within a tab component using Angular Material

I recently implemented a tab component with custom label templates. You can view the code and see how it works in this StackBlitz project. My question is, how can I add a cancel button to the top-right corner of the tabs? I don't need the button to do ...

React and TypeScript warns about possible undefined object

certificate?: any; <S.Contents>{certificate[0]}</S.Contents> <S.Contents>{certificate[1]}</S.Contents> <S.Contents>{certificate[3]}</S.Contents> If I set the type of props to `any` and use it as an index of an array, e ...

Best practices for Angular 2: determining whether to include a service in a component's provider or in a module

I'm finding it hard to determine whether a service should be placed in the component's provider within @Component() or in a NgModule(). For instance, if I have a service that fetches HTTP links for my FooterComponent, should it be included in th ...

Issues with Angular 5 components not functioning properly

I am experimenting with a way to show/hide a div based on a boolean value from an observable. After looking at the second answer in this Stack Overflow thread, I implemented the following code snippet that retrieves the document body width and uses it in a ...

Using Angular2 to import components and services from a module

I am currently developing a final Angular2 application with two modules: CoreModule: This module includes shared components and services. AppModule: The main module of the application. AppModule: /** * Created by jamdahl on 9/21/16. */ // Imports impo ...

Displaying a portion of the chart's key in a Highcharts BarChart

I need assistance displaying a partial legend (such as min, medium, max) for the X and Y axes, along with a horizontal dashed line at the medium point of the Y axis in a HighCharts BarChart. The graph is compact on the screen, serving as a summary of multi ...

Tips on updating primeng Panel Menu appearance with scss

I'm looking to customize the color of my panel menu to black. Below is the HTML code I am using. <p-panelMenu styleClass="font-bold text-xs m-0 w-11" [model]="items" [multiple]='false'></p-panelMenu> ...

Do I have to create all the classes returned when consuming a JSON web service in Angular/Typescript?

I would like to access this service: https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY I am interested in extracting only two pieces of data: "location" : { " ...

What resources are available for creating the framework of a TypeScript package in DefinitelyTyped?

I am interested in making contributions to by providing new types similar to what can be found on https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types. I believe there must be a way to create a package from scratch or get started. I have ...

Error message arising from a change in expression after it has been verified, specifically when using the ngClass directive

I've been attempting to add an active class to my route using a custom logic, but it seems that routerLinkActive is not working due to the dynamic nature of my parent and child routes. Here's the code snippet in question: <ul class="navbar-na ...

The @Input property in the template is not successfully assigning a value to the input variable in Angular 5

Exploring some Angular 5 experiments with PrimeNG, I encountered challenges related to Angular 5. After creating a component with the following template: <p>Chemi-table works! And now, a message from our sponsors: {{this.nombre}}</p> <p-dat ...

Setting default values and specifying available values for a class property in TypeScript

I'm curious about how to set a default value for a class property, as well as define all available values at once. For example: class MyClass{ isActive = -1; //Setting default value } class MyClass{ isActive: -1 | 0 | 1; //Defining all available ...

Eliminate apostrophes in a string by using regular expressions

Can someone help me with this word What is The Answer? I need to eliminate the space and apostrophe '. To remove spaces, should I use this method: data.text.replace(/ +/g, ""). But how can I remove the apostrophe? ...

TypeScript interface designed to capture objects containing a flexible number of values

In my possession is an object that looks like the following: { "0001": "a", "0002": "b", "0003": "c", ... } Is it possible for me to create a TypeScript interface that accurately represents this type? ...

What is the reasoning behind the Angular CLI's version displaying as 1 after the installation of version 7

I'm trying to update my global version of Angular CLI to the newest release. Why does ng v still display version 1.3.2 after the update? Just a heads up, I'm using nvm. Snapshot before updating... $ng -v _ _ ...

Dynamic property access using optional chaining in JavaScript

My attempt to utilize optional chaining, a feature provided by TypeScript for safely accessing dynamic properties, seems to be invalid. export const theme = { headers: { h1: { }, h6: { color: '#828286' }, }, } console.in ...

Changing the selection on multiple input fields in Angular

I am working with two select elements in my form. Based on the selected value from the first select, I am filtering data for the second select. Additionally, I have an option to add the same row of form if desired. My issue is that when I select a value fr ...