![](/img/trans.png)
[英]React Typescript: Argument of type '{ [x: number]: any; }' is not assignable to parameter of type
[英]Argument of type x is not assignable to parameter of type '{ x: any; }'
所以我正在学习 Angular 和 Typescript 并收到此错误。 似乎它要求我用类型来澄清一些事情,但我不确定。 我对此还是很陌生,所以感谢您的帮助!
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; }'.
成分页面的代码如下所示
export class Ingredient {
constructor( public name: string, public amount: number) {
}
}
给出错误的代码看起来像这样
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)
}
}
因为在这里, @Output() ingredientAdded = new EventEmitter<{Ingredient: any}>();
,您将发射类型指定为{Ingredient: any}
,作为具有Ingredient
属性的 object,但它应该具有name
和amount
属性的 object。
像这样。
@Output() ingredientAdded = new EventEmitter<{name: string, amount: number}>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.