このページでは

緩い等号比較型の強制

この警告カテゴリのスペルは[equality-type-coercion] です。

緩い等式比較型の強制

何が起こったのですか?

緩い比較演算子を使用して2つの値が等しいかどうか比較されました。

なぜ悪いのですか?

緩い比較演算子は、等しいかどうかをチェックする前に値を異なる型に強制することができます。これは予期しない結果につながる可能性があります。

以下は、矩形のリストとTextInput を使った例です。ユーザーが数値を入力すると、そのインデックスの矩形がハイライトされます。このコードには欠陥があります。なぜなら "" == 0 だからです。

import QtQuick

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

一般に、厳密な比較演算子===!== を使用してください。強制を意識する場合でも、明示的なキャストと厳密な比較を使用することをお勧めします。

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"
        }
    }
}

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.