The type x cannot be assigned to the parameter '{ x: any; }'

Currently learning Angular and Typescript but encountering an error. It seems to be related to specifying the type, but I'm unsure of the exact issue. Still new at this, so any guidance is appreciated!

    src/app/shopping-list-new/shopping-edit/shopping-edit.component.ts:24:31 - error TS2345: Argument of type 'Ingredient' is not assignable to parameter of type '{ Ingredient: any; }'.
  Property 'Ingredient' is missing in type 'Ingredient' but required in type '{ Ingredient: any; }'.

The code for the ingredients page is as follows:

 export class Ingredient {

  constructor( public name: string, public amount: number) {

  }
}

The code that triggers the error looks like this:

import { Component, OnInit, ElementRef, ViewChild, EventEmitter, Output,  } from '@angular/core';
import { Ingredient } from '../../shared/ingredient.model';

@Component({
  selector: 'app-shopping-edit',
  templateUrl: './shopping-edit.component.html',
  styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit {

  @ViewChild('nameInput') nameInputRef: ElementRef;
  @ViewChild('amountInput') amountInputRef: ElementRef;
  @Output() ingredientAdded = new EventEmitter<{Ingredient: any}>();


  constructor() { }

  ngOnInit(): void {
  }
  onAddItem() {
    const ingName = this.nameInputRef.nativeElement.value;
    const ingAmount = this.amountInputRef.nativeElement.value;
    const newIngredient = new Ingredient(ingName, ingAmount);
    this.ingredientAdded.emit(newIngredient)
  }
}

Answer №1

At this moment, when you use

@Output() ingredientAdded = new EventEmitter<{Ingredient: any}>();
, the specified emit type is {Ingredient: any}. However, it should actually be an object with properties name and amount.

It should look like this.

@Output() ingredientAdded = new EventEmitter<{name: string, amount: number}>();

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

Can the arrow function properly subscribe to an Observable in Angular and what is the accurate way to interpret it?

I'm currently working through the official Angular tutorial: https://angular.io/tutorial/toh-pt4 Within this tutorial, there is a component class that subscribes to a service: import { Component, OnInit } from '@angular/core'; import { He ...

Nested arrays in the JavaScript programming language

Is this JavaScript code accurate: var options = []; options.push(["Tom","Smith"]); options.push(["Mary","Jones"]); where each item in options is a two-element array of strings. I plan to add items to options using a for loop. Furthermore, can I i ...

Selecting a specific element within an Angular 4 component using a directive

How can I target a specific element within an Angular Directive component? I have a component named "highlighter" with a selector. This component includes content projection using ng-content. There is also a directive with the selector "highlighter inp ...

Why Does React Material-UI Switch Styling Keep Changing Sporadically?

Currently, I am trying to integrate a switch component from MUI into my code. Strangely enough, upon the initial page load, the switch appears exactly as it should - identical to the one displayed on the MUI site. However, upon reloading the page, it under ...

Unraveling the Structure of an Angular2 Project

Upon reviewing a downloaded typescript/Angular2 project structure that serves as the base code for extension, I find myself a bit puzzled. The confusion lies in how providers are initialized and provided in Angular 2. The current code snippet from the Ap ...

Attempting to create a universal logger factory using a functional approach

After reading Martin Fowler's blog on domain oriented observability, I was inspired to implement this concept without relying on classes. However, I encountered some challenges involving generics in TypeScript. Here is the snippet of my code (the erro ...

Issue encountered during the construction of the Angular project in production

$ ng build --prod Date: 2018-12-06T18:43:56.689Z Hash: e36e17503416de0fc128 Time: 7480ms chunk {0} runtime.ec2944dd8b20ec099bf3.js (runtime) 1.44 kB [entry] [rendered] chunk {1} main.9868d9b237c3a48c54da.js (main) 128 bytes [initial] [rendered] chunk {2} ...

The program is unable to identify the function .modal("show") upon adding HTML to the page

I'm currently developing a program that utilizes a click event handler to trigger an ajax request to my node server. The server then generates information within a handlebars partial and sends it back to the client using res.render("partials/scraped-a ...

Group a set of x elements together within a div, and then group a distinct number of elements together after every x-grouping

Is there a way to achieve a looping structure like this? For instance: Group every 2 divs into a new div, then (after every 2nd grouping) group every 3 divs together <div id="container"> <div></div> <div></div> ... </div& ...

How to Use Vue.js to Find the Nearest Div Element with a Specific

Below is the HTML code I am working with: <div id="app"> <div class="image"> <div class="overlay"> <p>Some overlay text</p> </div> <img src="https://placeimg.com/640/480/any" class="img-fluid"> ...

Troubleshooting issues with sorting and pagination in Angular Material table functionality

I am experiencing an issue with sorting and pagination using an Angular material table. The data is being fetched from a store as an observable and successfully displayed in the table. Even though the column names for sorting match the column definitions, ...

Employing plain Javascript (without the use of jQuery) to concatenate information from two JSON strings - encountering an error due to the absence of

Having a JSON stringified form data like this: {"name":"jack miller", "address":"123 main st"} I aimed to append more records but encountered an error saying "append is not a function." The desired outcome is to have both sets of records in this format: ...

What is more effective: utilizing document fragments or string concatenation for adding HTML to the DOM?

My task involves adding a collection of cards to the DOM. html <div class="card"> <div class="card-title">Card 1</div> <div class="card-subtext">This is card 1</div> </div> js let ...

The Angular CLI has encountered an issue - Syntax Error: Unexpected token {

After using Angular CLI to successfully create projects for some time, I encountered an issue today when attempting to serve a new project. ng serve Unexpected token { SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Modu ...

The NgModel function within *ngFor is executing more times than necessary during initialization

Displayed on screen are a list of tutorials with check boxes next to each tutorial's states. These tutorials and states are pulled from the database, each tutorial containing a name and an array of associated states. Here is the HTML code: <div c ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

The service class adorned with the NgModule decorator

Is it possible to manage dependencies for both services in the code snippet by adding a @NgModule({ imports: [... ]}) decorator to each service class? I would like to avoid adding the modules in app.module.ts as each service has different module dependenc ...

Steps for creating an Observable<Object[]> using data from 2 different API requests

My goal is to retrieve an Observable<MyResult[]> by making 2 separate API calls to load the necessary data. The first call is to load MyItem. The second call is to load Gizmos[] for each item. In a previous question, I loaded the second API into t ...

Exploring JQuery techniques for iterating through numerous JSON files to create dynamic quizzes

Hi everyone, I could really use some assistance right now. I am working on developing a front-end system for a quiz, but I have encountered a challenge with the back-end. The back-end provides 3 JSON files to work with. JSON1 contains category and title in ...

Verify and send form without reloading the page

I am currently facing an issue with jQuery validation and ajax form processing. My goal is to prevent a page refresh by using ajax, but I am struggling to determine the appropriate placement for the ajax code within the validation function in order to ensu ...