'How to pass in an optional parameter in request body conditionally?

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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source