打字稿减少返回错误的打字稿

时间:2020-04-16 01:10:33

标签: javascript typescript reduce

我正在尝试使用reduce将我的SQL响应总结为两个类别,即收入结果,但是我得到的是“ currentValue”(交易)类型作为返回而不是累加器(BalanceDTO),我仅返回累加器,如何将事务类型作为返回类型?

我真的不知道自己在做什么错,最近两个小时我完全被困住了。

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;

3 个答案:

答案 0 :(得分:2)

您缺少定义初始值和初始值的类型。初始值的类型将定义df.groupBy('State1').count().show() Py4JJavaError Traceback (most recent call last) org.apache.spark.SparkException: Job aborted due to stage failure: Task 1 in stage 725.0 failed 1 times, most recent failure: Lost task 1.0 in stage 725.0 (TID 13480, localhost, executor driver): java.util.regex.PatternSyntaxException: Dangling meta character &#39;*&#39; near index 0 函数的返回类型。

我建议将初始值定义为BalanceDTO,起始值为零

reduce

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

答案 1 :(得分:2)

您需要传递exams2pdf()的初始值作为exams2pdf()函数的第二个参数:

accumulator

答案 2 :(得分:1)

尝试这个。

    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