janmvtrinidad janmvtrinidad - 29 days ago 4x
TypeScript Question

How to do non short circuit condition in Typescript?

How to evaluate condition in non short circuit way in typescript?
Typescript does not allow

for boolean type.
The reason why I need a non short circuit checking is I call showErrors in function

Given this function

function isValue1Valid(){
if(value1 === 0) return true;
return false;

function isValue2Valid(){
if(value2 === 0) return true;
return false;

Then in my condition

if(isValue2Valid() & isValue2Valid()){
//Submit data

Although I can do it like this one

if(isValue2Valid() & isValue2Valid()){
//Submit data

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)
} else {
    // Submit data