aftab
aftab

Reputation: 693

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'.

Upvotes: 1

Views: 489

Answers (3)

matthew-e-brown
matthew-e-brown

Reputation: 3007

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).

Upvotes: 0

Vinod Sai
Vinod Sai

Reputation: 2122

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;

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could simplify the check to

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

Upvotes: 3

Related Questions