![](/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.