Ktr1000
Ktr1000

Reputation: 253

Typescript :Getter can't return array with custom type

Im getting errors when trying to return array with custom type from getter. Here is the error message:

Type 'Expense[]' is missing the following properties from type 'Expense': name, cost, priority

And here is my code:

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;

Upvotes: 0

Views: 297

Answers (1)

Tanmay_vijay
Tanmay_vijay

Reputation: 619

The problem here is both get and set must have the same type. In your case, set is working on single Expense object and get is returning Expense[].

Better solution would be create a append method for setter, as following code would not make sense

user.userExpenses = new Expense("1", 100, "1"); \\ it appends to expenses array

Here's what I would do

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];   
}

}

Upvotes: 2

Related Questions