Ad

Why I Can't Compare Boolean To Boolean In JavaScript React Using Flow?

- 1 answer

Hello I'm working with Flow to type checking my JavaScript code. My state for the following app looks like this:

type State = {
  todos: Array<{text: string, date: Object, completed: boolean}>,
};

After hit the command flow start I've got this error message: Cannot compare boolean to boolean.

The error message occurs at the following code snippet. There I toggle a todo item and I sort the list with a compare function.

this.setState(prevState => ({todos: t.sort(function(a,b) {
  return a.completed === b.completed ? 0 : a.completed > b.completed ? -1 : a.completed < b.completed ? 1 : 0
})}));
Ad

Answer

It doesn't like that you are using the relational comparison operator with Boolean values.

1: true > false
   ^ Cannot compare boolean [1] to boolean [2].
    References:
    1: true > false
       ^ [1]
    1: true > false
              ^ [2]

https://flow.org/try/#0C4JwrgpgBAfFBmBDANgZwkA


If you wanted to sort completed items before uncompleted ones, you can do:

(a, b) => a.completed ? (b.completed ? 0 : -1) : 1

Or cast the values to numbers:

(a, b) => Number(b.completed) - Number(a.completed)
Ad
source: stackoverflow.com
Ad