Search code examples
javascripttypescriptunion-types

How to only check true/false value for boolean or undefined union type in typescript?


I have two boolean | undefined variables

const condition1: boolean | undefined = xxx; // xxx is a return value from another method
const condition2: boolean | undefined = xxx;

I want to get the result of condition1 && condition2, but undefined should be excluded (meaning only the true/false matters, undefined is invalid and should not be compared)

so it should be

if(condition1 !== undefined && condition2 !== undefined) {
    return condition1 && condition2;
}
if(condition1 !== undefined && condition2 === undefined) {
    return condition1;
}
if(condition1 === undefined && condition2 !== undefined) {
    return condition2;
}
if(condition1 === undefined && condition2 === undefined) {
    return true;
}

how can I simplify the code?


Solution

  • You can put them into an array, filter out undefineds and then check that .every is true:

    return [condition1, condition2]
      .filter(cond => cond !== undefined)
      .every(Boolean);