运算符“+”不能应用于类型“{}”和 'number'
Operator '+' cannot be applied to types '{}' and 'number'
我正在尝试根据来自后端的查询计算我的应用程序中的银行余额,结果如下:
{
"previousBalance": 60,
"data": [
{
"id": "6fbc24fa-7262-4c82-8944-134201ca2524",
"bank_statement_id": "3d3a6fdc-66e3-412e-9c3a-493681a0504e",
"date": "2021-02-24T03:00:00.000Z",
"value": 333.33
},
{
"id": "98e1c331-a2cc-4e6c-b466-6e778bb1ad10",
"bank_statement_id": "d62c2bbb-fcf1-4227-9bdb-e7f7ba00099d",
"date": "2021-02-24T03:00:00.000Z",
"value": -200
},
{
"id": "1ede9e5c-3b29-450a-bfa3-655ab62ed489",
"bank_statement_id": "d62c2bbb-fcf1-4227-9bdb-e7f7ba00099d",
"date": "2021-02-24T03:00:00.000Z",
"value": -68.33
}
]
}
以此为目的,在每笔交易中留下每笔交易的余额值,逻辑如下
type Transaction = {
id: string,
bank_statement_id: string,
date: string,
value: number,
created_at: string,
updated_at: string,
}
const transactions: Transaction[] = [...];
const transactionsFormated = transactions.map((transaction:, index) => {
const totalBalance = transactions.reduce((acc: number, transaction, currentIndex) => {
if(currentIndex <= index) {
return acc + transaction.value;
}
return acc;
});
return {
...transaction,
balance: previousBalance + totalBalance,
}
});
然而,VSCode 指出 acc 参数是交易类型,而不是数字类型,此外还有标题中的消息post.
我该如何处理这个问题?
您缺少reduce方法的第二个参数,即初始值;如果没有,初始值是数组的第一个元素,这是一个事务。
...
const totalBalance = transactions.reduce((acc: number, transaction, currentIndex) => {
if(currentIndex <= index) {
return acc + transaction.value;
}
return acc;
}, 0); // <=== here add the initial value
...
我正在尝试根据来自后端的查询计算我的应用程序中的银行余额,结果如下:
{
"previousBalance": 60,
"data": [
{
"id": "6fbc24fa-7262-4c82-8944-134201ca2524",
"bank_statement_id": "3d3a6fdc-66e3-412e-9c3a-493681a0504e",
"date": "2021-02-24T03:00:00.000Z",
"value": 333.33
},
{
"id": "98e1c331-a2cc-4e6c-b466-6e778bb1ad10",
"bank_statement_id": "d62c2bbb-fcf1-4227-9bdb-e7f7ba00099d",
"date": "2021-02-24T03:00:00.000Z",
"value": -200
},
{
"id": "1ede9e5c-3b29-450a-bfa3-655ab62ed489",
"bank_statement_id": "d62c2bbb-fcf1-4227-9bdb-e7f7ba00099d",
"date": "2021-02-24T03:00:00.000Z",
"value": -68.33
}
]
}
以此为目的,在每笔交易中留下每笔交易的余额值,逻辑如下
type Transaction = {
id: string,
bank_statement_id: string,
date: string,
value: number,
created_at: string,
updated_at: string,
}
const transactions: Transaction[] = [...];
const transactionsFormated = transactions.map((transaction:, index) => {
const totalBalance = transactions.reduce((acc: number, transaction, currentIndex) => {
if(currentIndex <= index) {
return acc + transaction.value;
}
return acc;
});
return {
...transaction,
balance: previousBalance + totalBalance,
}
});
然而,VSCode 指出 acc 参数是交易类型,而不是数字类型,此外还有标题中的消息post.
我该如何处理这个问题?
您缺少reduce方法的第二个参数,即初始值;如果没有,初始值是数组的第一个元素,这是一个事务。
...
const totalBalance = transactions.reduce((acc: number, transaction, currentIndex) => {
if(currentIndex <= index) {
return acc + transaction.value;
}
return acc;
}, 0); // <=== here add the initial value
...