Rule javascript:S3403 says:
Comparing dissimilar types using the strict equality operators ===
and !==
will always return the same value, respectively false
and true
, because no type conversion is done before the comparison. Thus, such comparisons can only be bugs.
Sonarqube version: Version 8.9.5 (build 50698)
In the below example, Sonarqube incorrectly determines the type of variable ‘alsoDoY’ to be only a boolean, because that is what it is initially assigned to. However, the variable can change type to String ‘cancel’ conditionally, upon the condition needsUserInput
and the user selecting “cancel”.
let askQuestion = function(question, yes, no, cancel) {
//Updates the UI with the question,
//calls one of the the callback functions according to what the user selects.
}
let getUserInput = function(question) {
return new Promise(function(resolve,reject) {
askQuestion(question, function yes() {
resolve(true) ;
}, function no() {
resolve(false) ;
}, function cancel() {
resolve('cancel') ;
});
})
}
let doY = function() {
//...
}
let doX = async function(needsUserInput) {
let alsoDoY = false;
if(needsUserInput) {
alsoDoY = await getUserInput('You have requested X. Do you want to do Y as well?');
}
if(alsoDoY === 'cancel') {
throw(new Error('User cancelled operation.'));
}
//processing for X
if(alsoDoY) {
doY();
}
}
Javascript is not a strictly typed language, and Sonarqube errs by treating it that way.