简体   繁体   中英

How to write ternary operator logic for multiple conditions and for optional param?

trying to write logic for my validator functions that has objects we use as errorMap for the input validation, For below logic args.drugName is optional field if user provide text we just want to make sure its greater than 3 letters or in case of empty successCondition should be valid. So for the optional param in typescript how do we fix this issue?

main.js

   {
                errorKey: ValidationErrorEnum.InvalidDrugName,
                successCondition: (args: DrugPriceParam) => {
                    let isValid: boolean = false;
                    isValid = args.drugName.length >= 3 ? true : _.isEmpty(args.drugName) ? true : false;

                    // if (args.drugName && args.drugName.length >= 3) {
                    //         isValid = true;
                    // } else if (_.isEmpty(args.drugName)) {
                    //     isValid = true;
                    // }
                    return isValid;
     }

Error;

error TS2532: Object is possibly 'undefined'.

You could simplify the check to

return !args.drugName || args.drugName.length > 2;
//     if empty
//                       if longer then 2 characters

Its same as you write if condition

 (args.drugName && args.drugName.length >= 3) ? true : _.isEmpty(args.drugName) ? true : false;

There is new feature coming in js - optional chaining. you can use this currently using webpack plugin. https://github.com/tc39/proposal-optional-chaining

Using this we can simply write

args?.drugName?.length >= 3 ? true : _.isEmpty(args.drugName) ? true : false;

Because you're simply returning booleans, you don't actually need to use the ternary operator. You should be able to just pass the result of the comparison operations:

// if (args.drugName && args.drugName.length >= 3) {
//     isValid = true;
// } else if (_.isEmpty(args.drugName)) {
//     isValid = true;
// }

// Becomes:

isValid = (args.drugName && args.drugName.length >= 3) || _.isEmpty(args.drugName);

Don't forget about short-circuiting, either: If the first half of the ||is found to be true, then _.isEmpty won't even be run (and similarly, if the first half of the && is found to be false, then ...length >= 3 won't even be run).

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