Typescript:Getter无法返回具有自定义类型的数组

时间:2019-03-27 14:44:50

标签: javascript typescript

尝试从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;

1 个答案:

答案 0 :(得分:2)

这里的问题是getset必须具有相同的类型。在您的情况下,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];   
}

}