How to evaluate condition in non short circuit way in typescript?
Typescript does not allow &
or |
for boolean type.
The reason why I need a non short circuit checking is I call showErrors in function isValueValid
.
Given this function
function isValue1Valid(){
if(value1 === 0) return true;
showErrors1();
return false;
}
function isValue2Valid(){
if(value2 === 0) return true;
showErrors2();
return false;
}
Then in my condition
if(isValue2Valid() & isValue2Valid()){
//Submit data
}
Although I can do it like this one
if(isValue2Valid() & isValue2Valid()){
//Submit data
return;
}
showErrors1()
showErrors2()
But I feel to call it inside isValueValid function. In reality I always think to call show errors by default whenever there's an error.
To answer your question, you could do
if ([isValue2Valid(), isValue2Valid()].every(Boolean)) {
//Submit data
}
to evaluate all function calls and then combine their values. But you really shouldn't have isValueValid
call showError
in the first place. Instead, make your test functions return
the error messages, and then if there are any, show them:
function getValue1Error() {
if (value1 === 0) return null;
else return "error1";
}
function getValue2Error() {
if (value2 === 0) return null;
else return "error2";
}
// then:
const errors = [getValue1Error(), getValue2Error()] // or even better, just a loop over your fields
if (errors.some(Boolean)) {
for (let error of errors)
showError(error);
} else {
// Submit data
}