Home > Back-end >  Typescript: Operator ' ' cannot be applied to types 'number' and 'boolean&#
Typescript: Operator ' ' cannot be applied to types 'number' and 'boolean&#

Time:09-02

I have an array of strings representing numbers, and I want to be able to see how many times a certain string repeats on my array:

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
);

However, the operation inside my reduce function gives me the following error:

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

How can I tackle this?

CodePudding user response:

try this instead

const timesAppeared = numbers.reduce(
      (previousValue, currentValue) => previousValue   (currentValue === searchForValue ? 1 : 0),
      0
);

now the ternary operator returns a number, before you were creating a Boolean.

CodePudding user response:

Trying to keep the code relatively the same, just added the Number cast/constructor.

const numbers = ['1', '2', '3', '4', '6', '2', '9', '5', '2', '4', '8'];
const searchForValue = '2';
const timesAppeared = numbers.reduce(
      (previousValue, currentValue) => previousValue   Number(currentValue === searchForValue),
      0
);

Typescript loves types! Before your code was trying to add a boolean result to a number which isn't possible. All we did here was convert that boolean result to a number. However I would recommend learning how the ternary operation in the other answer works.

CodePudding user response:

prueba lo siguiente

searchForValue ='2';
timesAppeared = 0
for (let index = 0; index < numbers.length; index  ) {
    if(searchForValue==numbers[index]){
        timesAppeared=timesAppeared 1;
    }
    console.log(timesAppeared);
}
  • Related