Loose equality comparison type coercion

This warning category is spelled [equality-type-coercion] by qmllint.

Loose equality comparison type coercion

What happened?

Two values were compared for equality using the loose comparison operators.

Why is that bad?

The loose comparison operators can coerce values to a different type before checking for equality. This can lead to unexpected results.

Example

Here is an example with a list of Rectangles and a TextInput. When the user enters a number, the Rectangle at that index is highlighted. The code has a flaw. If the input is empty, the first rectangle is highlighted in red, because "" == 0.

 import QtQuick

 Item {
     TextInput {
         id: input
     }
     Repeater {
         model: 3
         Rectangle {
             // first rectangle is red on empty input
             color: input.text == index ? "red" : "blue"
         }
     }
 }

In general, use the strict comparison operators === and !==. Even if you are aware of the coercion, it is still recommended to use explicit casts and strict comparisons instead.

 import QtQuick

 Item {
     TextInput {
         id: input
     }
     Repeater {
         model: 3
         Rectangle {
             // check inputs, use explicit casts, and strict equality operators
             color: input.text.length !== 0
                    && Number(input.text) === index ? "red" : "blue"
         }
     }
 }