Typescript:运算符“+”不能应用于类型“number”和“boolean”

Dan*_*ona 0 javascript typescript

我有一个代表数字的字符串数组,我希望能够查看某个字符串在我的数组中重复了多少次:

const numbers = ['1', '2', '3', '4', '6', '2', '9', '5', '2'. '4', '8'];
const searchForValue = '2';
const timesAppeared = numbers.reduce(
      (previousValue, currentValue) => previousValue + (currentValue === searchForValue),
      0
);
Run Code Online (Sandbox Code Playgroud)

然而,我的reduce函数内部的操作给出了以下错误:

Operator '+' cannot be applied to types 'number' and 'boolean'.

我该如何解决这个问题?

Ale*_*lls 5

试试这个

const timesAppeared = numbers.reduce(
      (previousValue, currentValue) => previousValue + (currentValue === searchForValue ? 1 : 0),
      0
);
Run Code Online (Sandbox Code Playgroud)

现在,在创建布尔值之前,三元运算符返回一个数字。