[英]Typescript :Getter can't return array with custom type
我嘗試從getter返回具有自定義類型的數組時遇到錯誤。 這是錯誤消息:
Type 'Expense[]' is missing the following properties from type 'Expense': name, cost, priority
這是我的代碼:
import Expense from '../interfaces/expence';
class User {
firstName: string;
lastName: string;
totalCost: number;
private expenses: Expense[];
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = this.lastName;
}
set userExpenses(expence: Expense) {
this.expenses = [...this.expenses, expence]
this.totalCost += expence.cost
}
get userExpenses() {
return this.expenses
}
}
export default User;
interface Expense {
name: string
cost: number;
priority: string,
}
export default Expense;
這里的問題是get
和set
必須具有相同的類型。 在您的情況下, set
在單個Expense對象上工作,而get
返回Expense[]
。
更好的解決方案是為setter創建一個append方法,因為以下代碼沒有意義
user.userExpenses = new Expense("1", 100, "1"); \\ it appends to expenses array
這就是我要做的
class User {
firstName: string;
lastName: string;
totalCost:number;
private expenses: Expense[] ;
constructor(firstName: string,lastName: string) {
this.firstName = firstName;
this.lastName = this.lastName;
}
set userExpenses(expences: Expense[]) { //assignment
this.expenses = [...expences];
this.expenses.forEach(e => this.totalCost += e.cost);
}
get userExpenses() {
return this.expenses
}
addExpences(expences: Expense[]) { //append
expences.forEach(e => this.totalCost += e.cost);
this.expenses = [...this.expenses, ...expences];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.