简体   繁体   中英

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?

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

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

?? operator should be recommended.

return ((condition1 ?? condition2) && (condition2 ?? condition1)) ?? true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM