TheRealFakeNews
TheRealFakeNews

Reputation: 8143

How to require a group of optional parameters when an argument is provided for just one of the parameters?

I have a function with optional parameters like so

export const sentryException = (
  error: Error,
  contextLabel?: string,
  contextInfo?: Context,
  specificTags?: SentryTags,
) => {

The last 3, as shown, are optional. However, if contextLabel is provided, then contextInfo must be provided. I would prefer not to have to do

if ((contextLabel && !contextInfo) || (contextInfo && !contextLabel)) {
   // throw error
}

As you can imagine, this can get pretty messy as the number of required groupings of inputs grows!

Is there any way to require a subset of optional parameters must be passed in the functional call if a specific parameter is provided?


Edit: I just wanted to be clear that the // throw error comment isn't related to the error parameter. I mean that contextLabel and contextInfo must always both be defined (not undefined); otherwise, the function shouldn't be able to be executed.

So for simplicity, let's assume all the types are strings, except for error, then valid calls would be:

sentryException(err, 'a', 'b')
sentryException(err, 'a', 'b', 'c')
sentryException(err, undefined, undefined, 'c')
sentryException(err)

Upvotes: 1

Views: 251

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 186984

Sounds like a job for a simple set of function overloads where you create the specific argument type pairings that you want:

function sentryException(
  contextLabel?: undefined,
  contextInfo?: undefined,
  specificTags?: string,
): void

function sentryException(
  contextLabel: string,
  contextInfo: string,
  specificTags?: string,
): void

function sentryException(
  contextLabel?: string,
  contextInfo?: string,
  specificTags?: string,
): void {
  // implementation...
}

// good
sentryException()
sentryException(undefined, undefined, 'tag')
sentryException('a', 'b', 'tag')

// errors
sentryException('a')
sentryException('a', undefined, 'tag')

Playground

Upvotes: 2

Related Questions