I want to create an array that contains objects of Expense class. Everything seems great until I try to use “find” method on my array. Error: “Property ‘find’ does not exist on type ‘Expense[]’.”
class ExpenseTracker {
private data: Array<Expense>;
constructor() {
this.data = [];
}
public addExpense(_expense: Expense): void {
this.data.push(_expense);
}
public showExpenses(_id?: number): Expense | Expense[] {
if (_id) {
const expense = this.data.find((el) => el.id === _id);
return expense ? expense : this.data;
} else {
return this.data;
}
}
}
class Expense {
id: number;
name: string;
amount: number;
category: string;
description: string;
constructor(_id: number, _name: string, _amount: number, _category: string = '', _description: string = '') {
this.id = _id;
this.name = _name;
this.amount = _amount;
this.category = _category;
this.description = _description;
}
}
const expenseTracker = new ExpenseTracker();
const expense1 = new Expense(1, 'Groceries', 5.55);
expenseTracker.addExpense(expense1);
console.log(expenseTracker.showExpenses(1)); // Should show expense with id 1
console.log(expenseTracker.showExpenses()); // Should show all expenses
I googled for answer but didn’t find anything that could solve my problem.
New contributor
Informatyka Stosowana is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.