gpt4 book ai didi

javascript - typescript :Getter can't return array with custom type

转载 作者:行者123 更新时间:2023-12-01 01:08:31 25 4
gpt4 key购买 nike

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

最佳答案

这里的问题是 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];
}

}

关于javascript - typescript :Getter can't return array with custom type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55380032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com