Home > OS >  How to pass in an optional parameter in request body conditionally?
How to pass in an optional parameter in request body conditionally?

Time:02-17

I have an optional parameter called activationCodes which is defined as:

(property) PS.Components.Schemas.IC.activationCodes?: string[] | null | undefined

In my request body in my function, I only want to send in activationCodes as a field if another variable string is defined:

I tried it as:

  const reqBody: PS.Components.Schemas.IC = {
    description: input.description,
    outcome: input.outcome,
    activationCodes: aCode ? [aCode] : undefined,
  };

but this results in activationCodes: undefined in the reqBody if aCode is undefined. Is it possible to completely ignore the activationCodes field if aCode is undefined?

CodePudding user response:

Add it after:

const reqBody: PS.Components.Schemas.IC = {
  description: input.description,
  outcome: input.outcome,
};

if (aCode) reqBody.activationCodes = [aCode];
  • Related