简体   繁体   中英

Conditional chaining in JavaScript or TypeScript

Is there a syntax to add a function to a chain under conditions?

In this example, I would like myKey to be Joi.string().required() if modifier === true , but just Joi.string() if it is false :

function customJoi(modifier) {
  return Joi.object({
    myKey: Joi.string() //#If(modifier) .required() #EndIf
  });
}

I know I could do without this feature, with multiple steps. I'm just wondering if there is a nice way to write it concisely for large objects.

You can achieve that with a ternary .

function customJoi(modifier) {
    return Joi.object({
        myKey: modifier ? Joi.string().required() : Joi.string()
    });
}

You could take optional , if not required.

myKey: oi.string()[modifier ? 'required' : 'optional']()

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