Victor Thadeu
Victor Thadeu

Reputation: 107

Typescript Reduce returning wrong Type

I'm trying to use reduce to sum my SQL response in two categories, income and outcome, but I'm getting the "currentValue" (transaction) type as my return instead of the accumulator (BalanceDTO), I'm returning only the accumulator, how I'm getting the transaction type as my return type?

I really don't know what I'm doing wrong, I am completely stuck for the last two hours.

import { getRepository } from 'typeorm';

import Transaction from '../models/Transaction';

interface BalanceDTO {
  income: number;
  outcome: number;
}

class GetBalanceService {
  public async execute(): Promise<BalanceDTO> {
    const transactionRepository = getRepository(Transaction);

    const transactions = await transactionRepository.find();

    const balance = transactions.reduce(
      (accumulator: BalanceDTO, transaction): BalanceDTO => {
        accumulator[transaction.type] += transaction.value;
        return accumulator; //// HERE -- How it is returning the transactions type? ////
      },
    );

    return balance;
  }
}

export default GetBalanceService;

Upvotes: 2

Views: 2131

Answers (3)

kaveh
kaveh

Reputation: 2146

You need to pass an initial value for accumulator as the second argument of recude function:

const balance = transactions.reduce(
      (accumulator: BalanceDTO, transaction): BalanceDTO => {
        accumulator[transaction.type] += transaction.value;
        return accumulator; //// HERE -- How it is returning the transactions type? ////
      },
      {
          income: 0,
          outcome: 0
      }
    );

Upvotes: 2

kyun
kyun

Reputation: 10264

Try this one.

    const balance = transactions.reduce(
      (accumulator: BalanceDTO, transaction): BalanceDTO => {
        accumulator[transaction.type] += transaction.value;
        return accumulator;
      },{income: 0, outcome: 0} //you'd better set the initial value
    );

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Upvotes: 1

hoangdv
hoangdv

Reputation: 16127

You missing define initial value and type of initial value. Type of initial value will define return type of the reduce function.

I suggest define initial value as a BalanceDTO and start values is zero

const balance = transactions.reduce((accumulator, transaction) => {
  accumulator[transaction.type] += transaction.value;
  return accumulator;
}, {
    income: 0,
    outcome: 0,
} as BalanceDTO); // initialValue as a BalanceDTO

Now, balance is a BalanceDTO

Upvotes: 3

Related Questions